删除多次出现的数组元素 [英] Remove array elements that appear more than once
本文介绍了删除多次出现的数组元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
Array.Distinct()
叶不同的元素。如何从阵列中删除所有重复元素的包括的原单?
例如,给定该输入数组:
{狗,猫,鼠,狗,狗,鹦鹉,鼠标,猎犬}
我想获得这样的输出:
{猫,鹦鹉,猎犬}
解决方案
您可以使用一点的LINQ:
VAR单打= myArray的
.GroupBy(X => x)的
。凡(G => g.Count()== 1)
.SelectMany(G => G);
或者是这样的:
VAR单打= myArray的
.GroupBy(X => x)的
。凡(G =>!g.Skip(1)。任何())
.SelectMany(G => G);
- 的<一个href=\"http://msdn.microsoft.com/en-us/library/vstudio/system.linq.enumerable.groupby%28v=vs.100%29.aspx\"相对=nofollow>
GROUPBY
方法将收集所有相似的元素在一起。 - 的<一个href=\"http://msdn.microsoft.com/en-us/library/vstudio/system.linq.enumerable.where%28v=vs.100%29.aspx\"相对=nofollow>
其中,
方法过滤掉不符合特定条件组。我提供了两个备选方案的条件,但他们都做同样的事&MDASH;他们返回真只有当组包含一个元素
:-
g.Count()== 1
计算各组中的元素,并返回真正
如果数结果等于1。 -
!g.Skip(1)。任何()
收益真正
如果没有的元素后的第一个。这实际上是略高于更有效g.Count()== 1
,因为它不需要列举组中的所有元素,但它是一个有点混乱一些读者,所以在生产code引入此之前三思而后行。
-
- 最后,<一个href=\"http://msdn.microsoft.com/en-us/library/vstudio/system.linq.enumerable.selectmany%28v=vs.100%29.aspx\"相对=nofollow>
的SelectMany
将返回从结果集合中的所有元素。由于只有一个每个组中的元素,你就只剩下这是不重复的元素。
Array.Distinct()
leaves distinct elements. How can I remove all duplicate elements from Array including original one?
For example, given this input array:
{ Dog, Cat, Mouse, Dog, Dog, Parrot, Mouse, Hound }
I'd like to get this output:
{ Cat, Parrot, Hound }
解决方案
You can use a bit of Linq:
var singles = myArray
.GroupBy(x => x)
.Where(g => g.Count() == 1)
.SelectMany(g => g);
Or like this:
var singles = myArray
.GroupBy(x => x)
.Where(g => !g.Skip(1).Any())
.SelectMany(g => g);
- The
GroupBy
method will collect all similar elements together. - The
Where
method will filter out groups that do not meet a certain condition. I've provided two alternatives conditions, but they both do the same thing—they returntrue
only if the group contains exactly one element:g.Count() == 1
counts the number of elements in each group and returnstrue
if the result is equal to 1.!g.Skip(1).Any()
returnstrue
if there are no elements after the first. This is actually marginally more efficient thang.Count() == 1
because it doesn't require enumerating all elements in the group, but it's a bit confusing to some readers, so think twice before introducing this in production code.
- Finally,
SelectMany
will return all elements from in the result collection. Since there is only one element in each group, you're left with only those elements which are not duplicated.
这篇关于删除多次出现的数组元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文