【问题标题】:Linq .All returning true for empty collection [duplicate]Linq .All 为空集合返回 true [重复]
【发布时间】:2016-03-05 04:24:38
【问题描述】:

考虑以下代码:

static void Main(string[] args)
{
    List<string> items = new List<string>();
    string result = null;

    if(items.All(o => o == "ABC"))
    {
        result = "All";
    }
    else if(items.Any(o => o == "XYZ"))
    {
        result = "Any";
    }

    Console.WriteLine(result);
    Console.Read();
}

这会打印“全部”。

为什么 empty 列表满足 o == "ABC"

的“全部”条件

【问题讨论】:

  • 看源码here
  • 为什么是主观的,不是吗?杯子是半满还是半空? All 满足您的条件,因为没有。如果列表为空,您始终可以先检查。
  • 我认为您需要以相反的方式考虑它。 .All(...)true,只要不存在 false。如果列表为空,则不存在 false,所以它是 true

标签: c# linq


【解决方案1】:

根据 MSDN:-

Enumerable.All

如果源序列的每个元素都通过 在指定的谓词中进行测试,或者如果序列为空; 否则为假。

所以在你的情况下,因为 items 是一个空集合,它返回 true。

【讨论】:

    【解决方案2】:

    这是by design,也与universal quantifier ∀ 在数学集上的工作方式一致。

    【讨论】:

      猜你喜欢
      • 2018-04-28
      • 1970-01-01
      • 2011-01-12
      • 2019-04-27
      • 2019-10-04
      • 2020-04-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多