如果集合为空,LINQ Enumerable.All 始终返回 True

Ole*_*egI 2 .net c# 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; }
    }
Run Code Online (Sandbox Code Playgroud)

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

fub*_*ubo 6

这就是文档所说的。

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

执行

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;
}
Run Code Online (Sandbox Code Playgroud)

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