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”
If there is a potential for
Singleto fail because of no elements, useSingleOrDefault. It will return the single matching element, if one exists, or the default value for the type, which will benullfor reference types (classes). You will need to check against null prior to using the result.Another method pair to have in your bag is
FirstandFirstOrDefault. LikeSingle, they will return a matching element. UnlikeSingle, 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.