【问题标题】:linq Any operator with not equal(!=)linq 任何不等于(!=)的运算符
【发布时间】:2016-09-22 07:29:24
【问题描述】:

我无法理解 linq any 运算符。让我们考虑以下 sn-p 代码(使用 VS 2010 和 .Net 4.0)

List<string> sample = new List<string> { "a", "b", "c", "d" };
List<string> secondSample = new List<string> {  "b", "c" };

foreach (string s in sample)
{
    if(secondSample.Any(data=> data.ToString() == s))
        Console.WriteLine(s);
}

运行时会产生以下输出

b
c

这是我所期待的。但是,如果我将相等运算符 (==) 更改为 Not Equal(!=) 我会得到这个

a
b
c
d

不应该这样

a
d

如果我将 if 条件更改为

if(!(secondSample.Any(data=> data.ToString() == s)))

我明白了

a
d

所以我的问题是我是否以错误的方式解释 Any 运算符?不应该

if(secondSample.Any(data=> data.ToString() != s))

当来自secondSample 的值不在样本中时,评估为真

【问题讨论】:

    标签: c# .net linq list


    【解决方案1】:

    如果您想使用 != 运算符并且您期望 a d 作为结果,那么您应该使用 All 而不是 Any

     if(secondSample.All(data=> data.ToString() != s))
               Console.WriteLine(s);
    

    解释 如果secondSample 中只有一个元素不等于给定数据项(在您的sample 列表中),secondSample.Any(data=&gt; data.ToString() != s) 将为真,因此在您的情况下,它将始终为true 并且您会看到所有元素都写在控制台中。

    更好的解决方案有两个数组 A 和 B,如果你想要那些不在 B 中的 A 元素使用 LINQ 你可以尝试Except 如果你正在寻找共同的元素你可以尝试Intersect:

    List<string> A = new List<string> { "a", "b", "c", "d" };
    List<string> B= new List<string> { "b", "c" };
    
    var AnotInB = A.Except(B).ToList(); //a, d
    
    var AInB = A.Intersect(B).ToList(); //b, c
    

    【讨论】:

      【解决方案2】:

      != 在 Any 中表示 ALL 不相等。

      因此,如果有任何不相等的内容,则可以进行打印。 你猜怎么着,你总是至少有 1 个不相等。这就是你得到所有答案的原因。

      在你的另一句话中你说:不相等的那个你可以打印...

      还有更清楚的吗?

      【讨论】:

      • 你的解释也很好。简明扼要。我只能将一个标记为答案。否则我会标记两个
      【解决方案3】:

      任何运算符基本上都会问“集合中是否有任何元素可以回答谓词”。在你的情况下它是存在的,所以它是正确的输出。

      【讨论】:

        【解决方案4】:

        使用存在

        List<string> sample = new List<string> { "a", "b", "c", "d" };   
        
        List<string> secondSample = new List<string> { "b", "c" };
        
        foreach (string s in sample)
                {           
                  if (!secondSample.Exists(data => data.ToString() == s))            
                       Console.WriteLine(s);
                }
        

        【讨论】:

        • 如果您解释为什么 Any 运算符是错误的选择,您的答案会更好。
        【解决方案5】:

        当您更改为 !=

         if(secondSample.All(data=> (data.ToString() != s)))
        

        当你否定一个表达式时,内部的 or 变成了一个 and:“A or B”的否定变成了“Not A and Not B”。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2013-10-22
          • 1970-01-01
          • 2011-05-04
          • 2012-09-03
          相关资源
          最近更新 更多