Linq问题,在List为空时,All 方法返回值为什么是true

.Net技术 码拜 8年前 (2016-02-23) 949次浏览
 List<int> l2 = new List<int>();
bool ret2 = l2.All(t =>t>10);
Console.WriteLine(ret2);
上面这段代码,ret2值为true,没道理啊,直观感觉应该是false才对。
解决方案

16

内部代码应该是
bool istrue=true;
foreach(){
if(false){ istrue=false;break;}
}
所以没值时就返回true了

8

这里由不得你感觉,而是你得去迎合人家的思路(正所谓:吃人家饭,受人家管)
Linq问题,在List为空时,All 方法返回值为什么是true

8

8

换成Any 也行会好理解点。

8

Enumerable.All 的源码
http://referencesource.microsoft.com/#System.Core/System/Linq/Enumerable.cs,be4bfd025bd2724c

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;
}

MSDN https://msdn.microsoft.com/zh-cn/library/bb548541(v=vs.110).aspx
备注里有一句 true 假如源序列中的每个元素通过与指定谓词中的测试,或假如序列为空,则为否则为 false


CodeBye 版权所有丨如未注明 , 均为原创丨本网站采用BY-NC-SA协议进行授权 , 转载请注明Linq问题,在List为空时,All 方法返回值为什么是true
喜欢 (0)
[1034331897@qq.com]
分享 (0)