当结果为空时,LINQ会返回什么

本文翻译自:What does LINQ return when the results are empty

I have a question about LINQ query. 我有一个关于LINQ查询的问题。 Normally a query returns a IEnumerable<T> type. 通常,查询返回IEnumerable<T>类型。 If the return is empty, not sure if it is null or not. 如果返回为空,则不确定它是否为null。 I am not sure if the following ToList() will throw an exception or just a empty List<string> if nothing found in IEnumerable result? 如果在IEnumerable结果中找不到任何内容,我不确定以下ToList()是否会抛出异常或只是一个空List<string>

   List<string> list = {"a"};
   // is the result null or something else?
   IEnumerable<string> ilist = from x in list where x == "ABC" select x;
   // Or directly to a list, exception thrown?
   List<string> list1 = (from x in list where x == "ABC" select x).ToList();

I know it is a very simple question, but I don't have VS available for the time being. 我知道这是一个非常简单的问题,但我暂时没有VS可用。


#1楼

参考:https://stackoom.com/question/504v/当结果为空时-LINQ会返回什么


#2楼

It will return an empty enumerable. 它将返回一个空的可枚举。 It wont be null. 它不会是空的。 You can sleep sound :) 你可以睡觉:)


#3楼

.ToList returns an empty list. .ToList返回一个空列表。 (same as new List() ); (与新List()相同);


#4楼

它不会抛出异常,你会得到一个空列表。


#5楼

var lst = new List<int>() { 1, 2, 3 };
var ans = lst.Where( i => i > 3 );

(ans == null).Dump();  // False
(ans.Count() == 0 ).Dump();  // True

(Dump is from LinqPad ) (转储来自LinqPad


#6楼

Other posts here have made it clear that the result is an "empty" IQueryable, which ToList() will correctly change to be an empty list etc. 这里的其他帖子已经明确表示结果是一个“空”IQueryable,ToList()将正确地更改为空列表等。

Do be careful with some of the operators, as they will throw if you send them an empty enumerable. 请注意一些操作符,因为如果向它们发送一个空的枚举,它们将抛出。 This can happen when you chain them together. 将它们链接在一起时会发生这种情况。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值