最好的办法,以找出是否IEnumerable的<>具有独特的价值 [英] Best way to find out if IEnumerable<> has unique values

查看:140
本文介绍了最好的办法,以找出是否IEnumerable的<>具有独特的价值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有很多的code中,我做这样的事情

I have a lot of code in which I do something like this

bool GetIsUnique(IEnumerable<T> values)
{
    return values.Count() == values.Distinct().Count;
}

有没有更好更快更好的方式来做到这一点?

Is there a better faster nicer way to do this?

推荐答案

您的方法需要通过序列重复两次,有一些潜在的缺点的:

Your method needs to iterate through the sequence twice, with a few of potential drawbacks:

  1. 在迭代两次会比一次迭代任何显著规模的序列比较慢。
  2. 在某些序列会如果您尝试迭代他们不止一次地抛出一个异常;其他人可能会有不同的结果后续的迭代。
  3. 您的方法使用计数,需要在每次迭代整个序列。有没有理由你不应该打破,早早出局,只要你知道,有一个重复的值。
  1. Iterating twice will be slower than iterating once for sequences of any significant size.
  2. Some sequences will throw an exception if you try to iterate them more than once; others might return different results for subsequent iterations.
  3. Your method uses Count which needs to iterate the entire sequence each time. There's no reason why you shouldn't break-out early as soon as you know that there's a duplicate value.

下面的方法只需要通过序列重复一次,将打破,早早出局,只要任何重复的值遇到:

The following method only needs to iterate through the sequence once, and will break-out early as soon as any duplicate value is encountered:

bool GetIsUnique<T>(IEnumerable<T> values)
{
    var set = new HashSet<T>();

    foreach (T item in values)
    {
        if (!set.Add(item))
            return false;
    }
    return true;
}

这篇关于最好的办法,以找出是否IEnumerable的&LT;&GT;具有独特的价值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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