0

I'm new in using lambda expression sorry for a dumb question. Anyway consider this statement:

MethodInfo methodInfo = methodInfos.Where(k => k.GetCustomAttributes(typeof(DLMethodAttribute), false).Length > 0).Single();

My question is how can to identity if the predicate part has a result, considering methodinfos does not have any member having an attribute. I've got an error message telling, "Sequence contains no elements"

2 Answers 2

5

If there is a potential for Single to fail because of no elements, use SingleOrDefault. It will return the single matching element, if one exists, or the default value for the type, which will be null for reference types (classes). You will need to check against null prior to using the result.

var methodInfo = methodInfos.Where(k => predicate(k)).SingleOrDefault();
if (methodInfo != null)
{
     // use result
} 

Another method pair to have in your bag is First and FirstOrDefault. Like Single, they will return a matching element. Unlike Single, they will not throw an exception if more than one element exists that matches. Keep these in mind if you ever have a sequence that you need a matching element from, not necessarily the only matching element.

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

Comments

0

There is Any() Extension method that it can check for you.

if (methodInfos.Where(k => predicate(k)).Any())

Or--

if (methodInfos.Any(k => predicate(k)))

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.