简体   繁体   中英

enum_in.Single() is 1 and throws exception

I m executing the follwing code:

private static T FooException<T>(this IEnumerable<T> enum_in)    
{    
    try    
    {
        return enum_in.Single();
    }    
    catch(InvalidOperationException e)    
    {
        throw new XXXException(enum_in.Count(),  e   ...
    }    
}

and getting an InvalidOperationException . If I have a look at enum.Count() then ther is exactly one item. Thats what I don't understand. Are there any cases where the enum can be with count = 1 and running in InvalidOperationException ?

Not all implementations of Linq support all operations. Try using .First() instead.

Edit: To answer the comments about this not being true. Firstly, we don't know the concrete class of the variable, so even if you don't know of any implementation for which Single is unsupported, that doesn't mean it doesn't exist.

Furthermore I was thinking of the LINQ-To-Entity implementation. My source was the Microsoft Press book for exam 70-516 , which on page 423 states that there are some unsupported methods connected to paging:

Paging A paging operation returns a single, specific element from a sequence. The supported methods are First, FirstOrDefault, Skip and Take. The unsupported methods are ElementAt, ElementAtOrDefault, Last, LastOrDefault, Single , SingleOrDefault, SkipWhile and TakeWhile.

All of the examples also use First rather than Single in that chapter, which is why I took extra note of this. It's interresting that this contradicts the msdn documentation linked in the comments.

Single throws an InvalidOperationException if the enumerable is empty or the sequence contains more than one element. What do you get if you call SingleOrDefault()?

MSDN says

InvalidOperationException

The input sequence contains more than one element.

-or-

The input sequence is empty.

So I guess either you or MSDN is wrong. Did you try SingleOrDefault too? Maybe it is null.

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