简体   繁体   中英

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.

I recognise that the solution is to use .FirstOrDefault(), but I don't understand why my original effort doesn't work. 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. ?. 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.

The null conditional operator (?) tests for null before performing a member access operation. 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.

因为空集合不为null

First() explicitly throws an exception when the sequence contains no elements. FirstOrDefault() gives null if there are no elements (edit: or rather, it gives a default value, which for reference types is null ). What would you want First() to return from an empty sequence?

According to MSDN documentation:

    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. Since the collection is empty and you didn't use FirstOrDefault , an exception is thrown.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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