Home > front end >  Get duplicates from array c#
Get duplicates from array c#

Time:10-15

I've come across multiple examples of getting duplicates, and removing them from array. How do I do the opposite, to only getting the duplicates and removing the rest of the elements. from what I've learned from these examples: Duplicates containing no elements

What am I doing wrong? Any explanation would be awesome!

CodePudding user response:

numbers.Distinct() returns every single number in your array, just once. If you exclude these numbers from the array, you exclude everything. Instead you want to get the numbers that are present at least two times.

You can go the lazy (insane memory allocations) route (numbers.GroupBy(w => w).Where(w => w.Count() >= 2).Select(w => w.Key).ToArray()), or the performant way:

List<int> numbers = ...; // input numbers
var seen = new HashSet<int>();
var numbersWithDuplicates = new List<int>();

foreach(var number in numbers)
    if(!seen.Add(number)) // only care about numbers that appear multiple times
        numbersWithDuplicates.Add(number);

var uniques = numbers.Except(numbersWithDuplicates).ToList();

CodePudding user response:

Another approach using a Dictionary<int, int>, that tracks how many times each value appears:

Dictionary<int, int> counts = new Dictionary<int, int>();
foreach(int num in numbers)
{
    if (!counts.ContainsKey(num))
    {
        counts.Add(num, 0);
    }
    counts[num]  ;
}
duplicates = counts.Where(c => c.Value >= 2).Select(c => c.Key).ToArray();

This would give you the distinct values that were duplicated in array "duplicates".

You could also just use the Dictionary "counts" directly afterwards if you needed to know how many times each value appeared.

  • Related