2
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

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.