Is there a linq lambda search method that returns null, instead of throwing an exception, when searching a list?
My current solution is something like: (to avoid exception from being thrown)
if (list.Exists(x => x.Foo == Foo)) { var listItem = list.Find(x => x.Foo == Foo); }
It just feels wrong to repeat the expression.
Something like ...
var listItem = list.Find(x => x.Foo == Foo); if (listItem != null) { //Do stuff }
... feels better to me. Or is it just me?
Do you have a better approach on this one? (The solution don't have to be returning null, just a better solution is good)
Only throw an exception if it is truly an error. If it is expected behavior for the object to not exist, return the null. Otherwise it is a matter of preference. It certainly shouldn't be a matter of preference.
The major difference between First and FirstOrDefault is that First() will throw an exception if there is no result data for the supplied criteria whereas FirstOrDefault() returns a default value (null) if there is no result data.
Answers. First() will throw an exception if there is nothing in the result set. FirstOrDefault() will return the item or the default value. For an object this would be null.
FirstOrDefault(); It returns first item if does not match query. It is better practice to check the NULL after query.
var listItem = list.FirstOrDefault(x => x.Foo == Foo); if (listItem != null) { //Do stuff }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With