2012-09-01 45 views
4

我有以下代碼:如何檢查linq查詢中的空值?

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); 
} 

有沒有一種方法,我可以停止這種給人一種nullReference異常,如果:

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

了這兩種情況給我的問題,我不知道如何我可以使用IsNullOrEmpty檢查代碼 以檢查這兩個個案。

回答

2

如何

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); 
} 
+0

謝謝。這很好。幾個拼寫錯誤與Exeception :-) – Angela

+1

我會拋棄'Exception.Message'檢查。如果某個地方的異常將其消息設置爲空,我想知道該錯誤,所以我可以在源代碼中追蹤它。 –

2

在您選擇之前添加一個.Where(error.Exception != null && error.Exception.Message != null)只包含您想要的值不是null

+0

如果'error'爲null會怎麼樣? –

+0

然後再添加到我之前,我回答了 –

2

你可以使用May be Monad,先寫一個靜態類,並把With 擴展方法在類,然後只需使用With方法。在鏈接中還有一些其他類似的類型也很有幫助。

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); 
} 

,簡單地使用它:

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)); 

更新:製作更加清晰(類似於樣品中也存在鏈接),假設你有Person類層次結構:

public class Person 
{ 
    public Address Adress{get;set;} 
} 

public class Address 
{ 
    public string PostCode{get;set;} 
} 

現在你想獲得人的相關郵政編碼,並且你不知道輸入人是否爲空:

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); 
1

要過濾出空值,然後.Where(error => error.Exception != null)(該Exception對象應該始終有一個非空的消息,所以我就當檢測和修復那裏,如果有異常的錯誤)。

爲了在這種情況下表現不同, .Select(error => error.Exception == null ? "No Error" : error.Exception.Message)