简体   繁体   English

为什么IEnumerable不行?第一个()工作?

[英]Why doesn't IEnumerable?.First() work?

When I try to use ?.First() on an enumerable object, it throws the error "sequence contains no elements" when the object contains no items. 当我尝试在可枚举对象上使用?.First()时,当对象不包含任何项时,它会抛出错误“sequence contains no elements”。

I recognise that the solution is to use .FirstOrDefault(), but I don't understand why my original effort doesn't work. 我认识到解决方案是使用.FirstOrDefault(),但我不明白为什么我原来的努力不起作用。 Am I misunderstanding something or is it just 'one of those things'? 我误解了某些东西还是仅仅是“其中一件事”?

An empty sequence is not null , it's an actual object that simply has no items in it. 空序列不为null ,它是一个实际的对象,其中没有任何项目。 ?. doesn't call the member in question if the expression is null , which it's not, so First is called, and First throws an exception when it is passed an empty sequence. 如果表达式是不调用该成员国null ,这不是的话,那么First被调用, First抛出时,它传递了一个空序列异常。

The null conditional operator (?) tests for null before performing a member access operation. 在执行成员访问操作之前,空条件运算符(?)测试null。 The empty sequence is not null, it just contains no elements. 空序列不为空,它只包含没有元素。 So when you call First() it rightly fails, because there is no first element. 所以当你调用First()时它会失败,因为没有第一个元素。

因为空集合不为null

First() explicitly throws an exception when the sequence contains no elements. 当序列不包含元素时,First()显式抛出异常。 FirstOrDefault() gives null if there are no elements (edit: or rather, it gives a default value, which for reference types is null ). 如果没有元素,则FirstOrDefault()给出null (编辑:或者更确切地说,它给出了一个默认值,对于引用类型为null )。 What would you want First() to return from an empty sequence? 你想要First()从空序列返回什么?

According to MSDN documentation: 根据MSDN文档:

    int? length = customers?.Length; // null if customers is null   
    Customer first = customers?[0];  // null if customers is null  
    int? count = customers?[0]?.Orders?.Count();  // null if customers, the first         customer, or Orders is null  

Therefore, if your collection is not null, then the runtime will try to return the first element. 因此,如果您的集合不为null,则运行时将尝试返回第一个元素。 Since the collection is empty and you didn't use FirstOrDefault , an exception is thrown. 由于集合为空并且您没有使用FirstOrDefault ,因此抛出异常。

Link: https://msdn.microsoft.com/en-us/library/dn986595.aspx 链接: https//msdn.microsoft.com/en-us/library/dn986595.aspx

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM