【问题标题】:Checking Similar Values in a List C#检查列表 C# 中的相似值
【发布时间】:2018-07-06 18:49:30
【问题描述】:

我在 C# 中有以下代码,它检查列表中的项目是否相等(用于所有实际目的的整数列表):

intList.Distinct().Count() == 1

如果列表中的所有值都相等,则上述代码有效。

但是,如果我有一个场景:

intList = {1, 1, 0}

那么上面的代码就失败了。当列表中的所有值不相等时,有人可以建议我如何检查列表中的相似值。

【问题讨论】:

  • 你能澄清一下你所说的相似值是什么意思吗?您想要的不仅仅是真/假输出吗?你想要所有相同的值对吗?
  • 您要检查列表是否只包含唯一值吗?或者你的确切目标是什么?请尝试更具体并声明您预期的输入和输出。

标签: c# linq generics


【解决方案1】:

怎么样

bool isDup = intList.Count == intList.Distinct().Count();

【讨论】:

  • 我认为你的变量应该有isNotDup名字。
【解决方案2】:
if (intList.Distinct().Count() != intList.Count)
{
   // the list contained at least two values that were the same
}

【讨论】:

    【解决方案3】:

    Linq Group()Count()

    bool allUnique = intList.GroupBy(x => x).All(x => x.Count() == 1);
    

    通过使用HashSet()

    bool allUnique = new HashSet<int>(intList).Count == intList.Count;
    

    【讨论】:

    • 创建一个哈希集通常是个好主意,但不仅仅是使用它的计数属性。这是不必要的开销。从技术上讲,Distinct 的作用完全相同,只是没有创建新对象。
    • @Mafii .Distinct() 没有,但 .Distinct().Count() 实现了 IEnumberable 并创建了一个新对象 - 我有一个类似的 question 关于那个你可以看到 Distinct() 使用 Set&lt;&gt;HashSet&lt;&gt; 内部
    • 哦,直到。到时候我会把一切都拿回来。谢谢!
    猜你喜欢
    • 1970-01-01
    • 2019-02-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多