Returns unique values ​​without removing duplicates - c #

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

So this array ...

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


should only return:

[0, 2, 4]


Another way of the phrase would be to remove all duplicates as well as any unique values ​​that have ever been duplicated.

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


source to share

2 answers

The easiest way is to use LINQ, group by value, count the number of elements in each group, and then return keys for groups with a single value:

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


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



You can use the method GroupBy

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


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



All Articles