如何在C#中验证值集合是唯一的(不包含重复项)

Rub*_*ink 5 .net c# collections ienumerable unique

当然有一种简单的方法来验证一组值没有重复[ 在C#/ .NET中使用默认Comparisoncollection's' Type?不必直接内置,但应简短有效.

我看了很多,但我一直在打算使用collection.Count() == collection.Distinct().Count()哪些对我来说效率低下.我对结果不感兴趣,并且一旦发现重复就想要拯救,如果是这样的话.

(如果有人可以指出重复的话,我想删除这个问题和/或答案)

Jon*_*eet 9

好的,如果您只是想在找到副本后立即离开,那很简单:

// TODO: add an overload taking an IEqualityComparer<T>
public bool AllUnique<T>(this IEnumerable<T> source)
{
    if (source == null)
    {
        throw new ArgumentNullException("source");
    }
    var distinctItems = new HashSet<T>();
    foreach (var item in source)
    {
        if (!distinctItems.Add(item))
        {
            return false;
        }
    }
    return true;
}
Run Code Online (Sandbox Code Playgroud)

......或者使用All,正如你已经展示的那样.我认为在这种情况下理解起来有点简单......或者如果你确实想要使用All,为了清楚起见,我至少将方法组转换中的集合创建分开:

public static bool IsUnique<T>(this IEnumerable<T> source)
{
    // TODO: validation
    var distinctItems = new HashSet<T>();
    // Add will return false if the element already exists. If
    // every element is actually added, then they must all be unique.
    return source.All(distinctItems.Add);
}
Run Code Online (Sandbox Code Playgroud)


Rub*_*ink 7

内联它,你可以替换:

collection.Count() == collection.Distinct().Count()
Run Code Online (Sandbox Code Playgroud)

collection.All( new HashSet<T>().Add );
Run Code Online (Sandbox Code Playgroud)

(T集合元素的类型在哪里)

或者你可以将上面的内容提取到辅助扩展方法[1],这样你就可以说:

collection.IsUnique()
Run Code Online (Sandbox Code Playgroud)

[1]

static class EnumerableUniquenessExtensions
{
    public static bool IsUnique<T>(this IEnumerable<T> that)
    {
        return that.All( new HashSet<T>().Add );
    }
}
Run Code Online (Sandbox Code Playgroud)

(正如乔恩在他的回答中指出的那样,人们应该将两条线分开并评论,因为'可爱'通常不是一个好主意)