0

Is there a way that I could return duplicate values from an array in C#? also im looking to write a small algorithm that would return the most number of duplicate values in an array. for example

[1, 2,2,2 3,3] I need to return the duplicate values with the most number of occurrences and the number of occurrences as well.

I think I saw some post which said that It could be done using Linq but I have no clue what Linq is

Any help would be much appreciated.

0

2 Answers 2

4

Try this:

int[] data = new int[] { 1, 2, 2, 2, 3, 3 };
IGrouping<int, int> mostOccurrences = data
    .GroupBy(value => value)
    .OrderByDescending(group => group.Count())
    .First();

Console.WriteLine("Value {0} occurred {1} time(s).", mostOccurrences.Key, mostOccurrences.Count());

Note that if multiple values occur the same number of times (such as if you added another 3 to that list), the above code will only list one of them. To handle that situation, try this:

int[] data = new int[] { 1, 2, 2, 2, 3, 3, 3 };
var occurrenceInfos = data
    .GroupBy(value => value)
    .Select(group =>
        new {
            Count = group.Count(),
            Value = group.Key
        }
    );
int maxOccurrenceCount = occurrenceInfos.Max(info => info.Count);
IEnumerable<int> maxOccurrenceValues = occurrenceInfos
    .Where(info => info.Count == maxOccurrenceCount)
    .Select(info => info.Value);

foreach (int value in maxOccurrenceValues)
    Console.WriteLine("Value {0} occurred {1} time(s).", value, maxOccurrenceCount);
Sign up to request clarification or add additional context in comments.

3 Comments

Hi this line seem to throw an invalid operations exception on this line var maxOccurrenceCount = occurrenceInfos.Max(info => info.Count);
Hi sorry it was my stupidity as the data array was empty! works like a charm, but I am confused how to return the values stored in maxOccurenceValues.
I updated my answer so the variables are declared with explicit types so it's a little clearer. It really depends on what you want to use maxOccurrenceValues for, but since it's of type IEnumerable<int> you can use it as-is, or if you need an array call maxOccurrenceValues.ToArray().
2

Here's my take on this:

var data = new[] { 1, 2, 2, 2, 3, 3, };

var occurences =
    data
        .ToLookup(x => x)
        .ToDictionary(x => x.Key, x => x.Count());

var mostOccurences =
    occurences
        .OrderByDescending(x => x.Value)
        .First();

These will give you the following results:

results

1 Comment

Nice one, the only thing is that maybe you don't need the dictionary: var occurences = from d in data.ToLookup(x => x) select new { d.Key, Count = d.Count() };

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.