内容目录
当集合为 null 时,代码如下:
List<int>? _a = null;
List<int>? _b = null;
var a = _a?.Any() == false;
var b = _a?.Any() == true;
var c = _b?.Any() == false;
var d = _b?.Any() == true;
当集合为 null 时,?.Any() == false 、?.Any() == true ,结果都是 false。

当集合为 不为 null ,元素数量为 0 时,代码如下:
List<int>? _a = new List<int>();
List<int>? _b = new List<int>();
var a = _a?.Any() == false;
var b = _a?.Any() == true;
var c = _b?.Any() == false;
var d = _b?.Any() == true;

结论是,能够正确表达意图。
如果想判断两个集合都不为 null,并且都有元素时:
List<int>? _a = null;
List<int>? _b = new List<int>();
var result = _a?.Any() == true && _b?.Any() == true;

其中一个有不为 null 且有元素:
List<int>? _a = null;
List<int>? _b = new List<int>()
{
1,2
};
var result = _a?.Any() == true || _b?.Any() == true;

判断两者都是 null 或 没有元素,这个就麻烦,难写,例如下面代码就有 bug:
List<int>? _a = null;
List<int>? _b = new List<int>();
var result = !(_a?.Any() == true && _b?.Any() == true);
_b = new List<int>() { 1,2,3,4};
result = !(_a?.Any() == true && _b?.Any() == true);
最好还是写扩展,不要试图在一行代码解决所有:
internal static bool IsNullOrEmpty<T>(this IEnumerable<T>? source)
{
if (source == null) return true;
if (source.Count() == 0) return true;
return false;
}
语法糖虽然好用,但是需要注意规范,不然会写出黑暗代码。

文章评论