InvalidOperationException when using First()
var key = bindingList.Selec开发者_如何学运维t((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
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.
精彩评论