You can use Maybe Monad , First write a static class and put With in this class, then just use the With method. There are some other similar types in the link that are also useful.
public static TResult With<TInput, TResult>(this TInput o, Func<TInput, TResult> evaluator) where TResult : class where TInput : class { if (o == null) return null; return evaluator(o); }
And use it simply:
var exceptions = ModelState.SelectMany(x => x.With(y=>y.Value).With(z=>z.Errors)) .Select(error => error.With(e=>e.Exception).With(m=>m.Message));
Update: to make it more clear (a similar example also exists in the link), suppose you have a Person class hierarchy:
public class Person { public Address Adress{get;set;} } public class Address { public string PostCode{get;set;} }
Now you want to get the zip code associated with the person, and you do not know that the person you enter is null or not:
var postCode = // this gives address or null, if either person is null or its address person.With(x=>x.Address) // this gives post code or returns null, // if previous value in chain is null or post code is null .With(x=>x.PostCode);
source share