返回唯一值,而不删除重复 - C# [英] Return unique values without removing duplicates - C#

查看:135
本文介绍了返回唯一值,而不删除重复 - 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.

所以这阵...

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

应该只返回:

[0, 2, 4]

另一种表达,这将是删除所有重复,以及那是有史以来所有的唯一值复制。

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

我是从一个JavaScript背景的和我还是有点不稳与C#语法。 :)

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

推荐答案

的最简单的方法是使用LINQ,由值分组,各组中的计数元件的数量,然后返回键基与单个值

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

这篇关于返回唯一值,而不删除重复 - C#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆