Eu Lupu
Eu Lupu

Reputation: 371

InvalidOperationException when using First()

var key = bindingList.Select((item, index) => new {item})
                    .Where(x => x.item.Description == description)
                    .Select(x => x.item.Key)
                    .First();

I know that I can use FirstOrDefault() avoiding the exception but the default in this case (int 0) is not what I want, I need a -1 as a default. Is there any other way to do this without actually catching the exception?

Thanks, Mihail

Upvotes: 2

Views: 1453

Answers (1)

Kirk Woll
Kirk Woll

Reputation: 77576

Try using DefaultIfEmpty:

var key = bindingList.Select((item, index) => new {item})
                .Where(x => x.item.Description == description)
                .Select(x => x.item.Key)
                .DefaultIfEmpty(-1)
                .First();

The DefaultIfEmpty LINQ operator will return the sequence unaltered if it's not empty, but otherwise return a sequence only containing the specified value (in this case -1) if the sequence is empty. At that point, you can safely invoke First without worrying about an exception being thrown.

Upvotes: 2

Related Questions