全部执行,但列表为空

时间:2014-03-18 14:30:53

标签: c# linq

namespace ConsoleApplication15
{
  using System;
  using System.Collections.Generic;
  using System.Linq;

  public class Test
  {
    public string Status { get; set; }
  }

  public static class Program
  {
    static void Main(string[] args)
    {
      var list = new List<Test>();

      if (list.Any(x => x.Status == "Tester"))
      {
        Console.WriteLine("This Line will not execute");
      }

      if (list.All(x => x.Status == "Tester"))
      {
        Console.WriteLine("This line will execute");
      }
    }
  }
}

任何人都可以向我解释为什么行所有条件都被执行而许多人没有? 全部 - &GT;该列表不包含项目!

4 个答案:

答案 0 :(得分:4)

  

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

根据MSDN声明,您得到的结果是 True Enumerable.All() Method MSDN

答案 1 :(得分:3)

如果源序列(在您的情况下为列表)为空,

Enumerable.All将返回true。

这是Enumerable.All

的记录
  

返回值:如果源序列的每个元素都通过了测试,则为true   指定谓词,或序列为空;除此以外,   假的。

答案 2 :(得分:3)

如果你看一下All方法的实现:

public static bool All<TSource>(this IEnumerable<TSource> source, Func<TSource, bool> predicate)
{
    foreach (TSource element in source) 
    {
       if (!predicate(element)) return false;
    }
    return true;
}

你可以看到它试图迭代元素。但由于源序列中没有元素,它会立即返回 true 。另一方面,Any方法:

public static bool Any<TSource>(this IEnumerable<TSource> source, Func<TSource, bool> predicate) 
{
    foreach (TSource element in source) 
    {
       if (predicate(element)) return true;
    }
    return false;
}

同样的事情,但它会立即返回false

答案 3 :(得分:3)

.All()会执行,因为列表中的每个项目都满足条件,这确实是真的。列表中没有项目,零项目符合条件。那是全部

.Any()无法执行,因为匹配项的数量为零。任何都必须大于零。

这样想:每次我吃长颈鹿,All时间,我会消化不良。但我从未真正吃过长颈鹿。它没有发生Any次。

相关问题