LINQ Enumerable。如果集合为空,则始终返回True

时间:2017-11-15 14:24:12

标签: c# .net linq

    class Program
    {
        static void Main()
        {
            var list = new List<Foo>();
            var a = list.All(l => l.BoolBar == true);//true
            var s = list.All(l => l.Bar.Contains("magicstring"));//true
        }
    }
    public class Foo
    {
        public bool BoolBar{ get; set; }
        public string Bar{ get; set; }
    }

基于这个片段,我想知道为什么Linq框架创建者选择使用此解决方案进行空集合?此外,由于Visual Studio和Linq都是MS产品,为什么如果用户在执行之前没有检查集合是否为空,智能感知不会发出警告.All?我认为这会导致很多意想不到的结果。

1 个答案:

答案 0 :(得分:4)

这就是Documentation所说的。

  

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

Implementation

public static bool All<TSource>(this IEnumerable<TSource> source, Func<TSource, bool> predicate) 
{
    if (source == null) throw Error.ArgumentNull("source");
    if (predicate == null) throw Error.ArgumentNull("predicate");
    foreach (TSource element in source) {
        if (!predicate(element)) return false;
    }
    return true;
}

所以很明显,如果IEnumerable中没有项目,则会跳过foreach循环,直接返回true