如何验证值的集合是唯一的(不包含重复)在C# [英] How do I verify a collection of values is unique (contains no duplicates) in C#

查看:136
本文介绍了如何验证值的集合是唯一的(不包含重复)在C#的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当然,还有一个简单的方法来验证值的集合已经没有重复[使用默认的比较集合键入]在C#/。NET?不必直接建在但应是短和高效。

Surely there is an easy way to verify a collection of values has no duplicates [using the default Comparison of the collection's Type] in C#/.NET ? Doesn't have to be directly built in but should be short and efficient.

我已经看了很多,但我不停的用例 collection.Count()== collection.Distinct()。COUNT()这对我来说是无效的。我不感兴趣的结果,并希望摆脱困境,只要我发现一个重复的,应该是这样的话。

I've looked a lot but I keep hitting examples of using collection.Count() == collection.Distinct().Count() which for me is inefficient. I'm not interested in the result and want to bail out as soon as I detect a duplicate, should that be the case.

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

(I'd love to delete this question and/or its answer if someone can point out the duplicates)

推荐答案

好吧,如果你只是想离开,只要重复被发现,这是简单的:

Okay, if you just want to get out as soon as the duplicate is found, it's simple:

// 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;
}

...或使用所有,因为你已经展示。我认为这是稍微简单在这种情况下,了解...或者,如果你的执行的要使用所有,我会在至少单独建立了一套从方法组转换为清晰:

... or use All, as you've already shown. I'd argue that this is slightly simpler to understand in this case... or if you do want to use All, I'd at least separate the creation of the set from the method group conversion, for clarity:

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);
}

这篇关于如何验证值的集合是唯一的(不包含重复)在C#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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