且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如果使用SingleOrDefault()并在数字列表中搜索不在列表中的数字,如何返回null?

更新时间:2023-11-26 08:18:28

您可以使用DefaultIfEmpty为空集合指定自定义默认值:

You can use DefaultIfEmpty to specify a custom default value for an empty collection:

var value = numbers.Where(MyFilter)
    .DefaultIfEmpty(-1) //or any other default value you want
    .Single(); //OrDefault not needed; DefaultIfEmpty ensures there is an item