5

像这样的列表:

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

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

但是,我想要相反的。我希望它删除所有重复的数字,留下唯一的数字。

所以列表将显示:1,5。

这将如何完成?

4

3 回答 3

12

一种方法是

var singles = numbers.GroupBy(n => n)
                     .Where(g => g.Count() == 1)
                     .Select(g => g.Key); // add .ToArray() etc as required
于 2013-09-20T09:43:38.190 回答
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 对乔恩的回答所评论的那样:

var allUniques = numbers.GroupBy(i => i)
    .Where(group => !group.Skip(1).Any())
    .Select(group => group.Key).ToList();
于 2013-09-20T09:49:11.300 回答
4
var cleanArray = numbers.GroupBy(x=>x)
  .Where(x=>x.Count() == 1)
  .SelectMany(x=>x)
  .ToArray();
于 2013-09-20T09:43:29.687 回答