How can I check for null inside a linq query?

I have the following code:

protected IEnumerable<string> GetErrorsFromModelState() { var exceptions = ModelState.SelectMany(x => x.Value.Errors .Select(error => error.Exception.Message)); var errors = ModelState.SelectMany(x => x.Value.Errors .Select(error => error.ErrorMessage)); return exceptions.Union(errors); } 

Is there a way I could stop this by giving a nullReference Exception if:

 error.Exception is null or if error.Exception.Message is null 

Both cases give me problems, and I'm not sure how I can code this with IsNullOrEmpty checking for cases .

+4
source share
4 answers

What about

 protected IEnumerable<string> GetErrorsFromModelState() { var exceptions = ModelState.SelectMany(x => x.Value.Errors .Where(error => (error != null) && (error.Exception != null) && (error.Exception.Message != null)) .Select(error => error.Exception.Message)); var errors = ModelState.SelectMany(x => x.Value.Errors .Where(error => (error != null) && (error.ErrorMessage != null)) .Select(error => error.ErrorMessage)); return exceptions.Union(errors); } 
+2
source

Add to .Where(error.Exception != null && error.Exception.Message != null) before you select only those where the required values ​​are not null .

+2
source

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); 
+2
source

To filter the zeros, then .Where(error => error.Exception != null) (the Exception object should always have a non-zero message, so I would consider it an error to detect and fix there if there is an exception).

To behave differently in this case, then, for example, .Select(error => error.Exception == null ? "No Error" : error.Exception.Message) .

+1
source

All Articles