ssamakar
ssamakar

Reputation: 65

Return unique values without removing duplicates - C#

I know there are many answers about returning unique values in an array after removing duplicates, but isn't every element in an array unique after you remove the duplicates? I want to only return values that are unique prior to removing any duplicates. If the element repeats in the original array, I don't want it in my final array.

So this array...

[0, 1, 1, 2, 3, 3, 3, 4]

should return only:

[0, 2, 4]

Another way to phrase this would be to remove all duplicates as well as all unique values that were ever duplicates.

I'm coming from a JavaScript background and am still a little shaky with C# syntax. :)

Upvotes: 3

Views: 354

Answers (2)

Selman Genç
Selman Genç

Reputation: 101681

You can use GroupBy method

var uniqueNumbers = numbers.GroupBy(x => x)
                   .Where(x => x.Count() == 1)
                   .Select(g => g.Key)
                   .ToArray();

This will basically group all the numbers and then take those group that has one number in it.

Upvotes: 6

Jon Skeet
Jon Skeet

Reputation: 1500665

The simplest approach is to use LINQ, grouping by the value, counting the number of elements in each group, and then returning the keys for groups with a single value:

var singleOccurrences = array.GroupBy(x => x)
                             .Where(g => g.Count() == 1)
                             .Select(g => g.Key)
                             .ToArray();

If you really need this to be efficient for large inputs, you could write your own method keeping track of "elements with a single value" and "elements with more than one value" as sets. I'd start with this though :)

Upvotes: 6

Related Questions