C#在列表中获取非重复项

时间:2013-09-20 09:42:24

标签: c#

使用如下列表:

int[] numbers = {1,2,2,3,3,4,4,5};

我可以使用Distinct()函数删除重复项,因此列表将显示为:1,2,3,4,5

然而,我想反过来。我希望它删除所有重复的数字,留下我唯一的数字。

所以列表将为:1,5。

如何做到这一点?

3 个答案:

答案 0 :(得分:13)

一种方法是

var singles = numbers.GroupBy(n => n)
                     .Where(g => g.Count() == 1)
                     .Select(g => g.Key); // add .ToArray() etc as required

答案 1 :(得分:9)

对于它的价值,一个检查序列是否包含多于N元素的扩展名:

public static bool CountMoreThan<TSource>(this IEnumerable<TSource> source, int num)
{
    if (source == null)
        throw new ArgumentNullException("source");
    if (num < 0)
        throw new ArgumentException("num must be greater or equal 0", "num");

    ICollection<TSource> collection = source as ICollection<TSource>;
    if (collection != null)
    {
        return collection.Count > num;
    }
    ICollection collection2 = source as ICollection;
    if (collection2 != null)
    {
        return collection2.Count > num;
    }

    int count = 0;
    using (IEnumerator<TSource> enumerator = source.GetEnumerator())
    {
        while (++count <= num + 1)
            if (!enumerator.MoveNext())
                return false;
    }
    return true;
}

现在它简单有效:

var allUniques = numbers.GroupBy(i => i)
    .Where(group => !group.CountMoreThan(1))
    .Select(group => group.Key).ToList();

DEMO

或者,正如@KingKing对Jon的回答所评论的那样:

var allUniques = numbers.GroupBy(i => i)
    .Where(group => !group.Skip(1).Any())
    .Select(group => group.Key).ToList();

答案 2 :(得分:5)

var cleanArray = numbers.GroupBy(x=>x)
  .Where(x=>x.Count() == 1)
  .SelectMany(x=>x)
  .ToArray();