Return unique values without removing duplicates - C#

时间秒杀一切 提交于 2019-12-12 15:34:52

问题


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. :)


回答1:


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 :)




回答2:


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.



来源:https://stackoverflow.com/questions/26287686/return-unique-values-without-removing-duplicates-c-sharp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!