检查 IEnumerable(Of T) 中是否没有元素 - Linq 元素和量词运算符
对于我的函数,
IEnumerable<CallbackListRecord> LoadOpenListToProcess(CallbackSearchParams usp);
当序列不包含元素(应该如此)时,此行错误
CallbackListRecord nextRecord = CallbackSearch.LoadOpenListToProcess(p).First();
我已将其更改为以下
CallbackListRecord nextRecord = null;
IEnumerable<CallbackListRecord> nextRecords = CallbackSearch.LoadOpenListToProcess(p);
if (nextRecords.Any())
{
nextRecord = nextRecords.First();
}
是否有更好、更简单或更优雅的方法来确定 IEnumerable 序列是否没有元素?
For my function
IEnumerable<CallbackListRecord> LoadOpenListToProcess(CallbackSearchParams usp);
This line errors when the sequence contains no elements (as it should)
CallbackListRecord nextRecord = CallbackSearch.LoadOpenListToProcess(p).First();
I have changed it to the following
CallbackListRecord nextRecord = null;
IEnumerable<CallbackListRecord> nextRecords = CallbackSearch.LoadOpenListToProcess(p);
if (nextRecords.Any())
{
nextRecord = nextRecords.First();
}
Are there better, easier or more elegant ways to determine if the IEnumerable sequence has no elements?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您可以将代码缩短为以下
nextrecord 将包含第一个元素(如果有一个元素)或 null(如果集合为空)。
You can shorten the code to the following
nextrecord will either contain the First element if there was one or null if the collection was empty.
您可以添加这样的扩展方法:
You could add an extension method like this:
如果您预计序列中可能存在空值,您可以自己处理枚举器。
If you are anticipating that there could be null values in the sequence, you could handle the enumerator yourself.
您应该尽量避免枚举它超过必要的次数(即使短路,如
First
和Any
) - 怎么样:这对于类来说效果很好(因为您可以只需将引用与 null 进行比较)。
You should try to avoid enumerating it more times than necessary (even if short-circuited, like
First
andAny
) - how about:This works well with classes (since you can just compare the reference to null).