2014-10-10 55 views
2

我有成功生成一個列表這個LINQ的說法,如果屬性不爲nullLINQ檢查字符串屬性中生成ToList NULL()

results.AddRange(m_CTS.Entity.Where(x => x.Property.Contains(search)).ToList()); 

但是,如果x.property爲null,則它的錯誤,所以我想嘗試檢查它是否爲空,如果它不爲空,繼續構建列表。

我都試過了,

results.AddRange(m_CTS.Entity.Where(x => x.Property == null ? "" : x.Property.Contains(search)).ToList()); 

但是,這也錯誤,我究竟做錯了什麼?

由於提前

+0

從第二個查詢中得到什麼錯誤? – DavidG 2014-10-10 08:40:29

+2

將'(x => x.Property == null?「」'更改爲'(x => x.Property == null?false' – artm 2014-10-10 08:40:33

回答

4

x.Property.Contains(search)返回bool所以三元運算符的另一面應該做到這一點:

x => x.Property == null ? false : x.Property.Contains(search) 

或者乾脆:

x => x.Property != null && x.Property.Contains(search) 
7

你應該只檢查null這樣的:

x.Property != null && x.Property.Contains(search) 

Where預計返回bool聲明瞭,但是你的第一個表達式返回string等一個返回bool。所以它不編譯。

&&之所以會工作,是因爲short-circuiting。如果x.Property != null將false評估爲false,則不會評估第二個表達式,您將不會得到該異常。

0

入住這

results.AddRange(m_CTS.Entity.Where(x => x.Property != null && x.Property.Contains(search)).ToList()); 
1

這可能是你正在尋找

class Persons 
    { 
     public int Id { get; set; } 
     public string Name { get; set; } 
    } 

    class Program 
    { 
     static void Main(string[] args) 
     { 
      var personCollection = new List<Persons> 
      { 
       new Persons {Id = 1, Name = "Manu"}, 
       new Persons {Id = 2, Name = "Lijo"}, 
       new Persons {Id = 3, Name = "John"}, 
       new Persons {Id = 4, Name = null}, 
       new Persons {Id = 5, Name = null}, 
      }; 

      List<string> personsNames = 
       personCollection.Where(x => x.Name != null && x.Name.Contains("j")).Select(x => x.Name).ToList(); 


      foreach (var personame in personsNames) 
      { 
       Console.WriteLine(personame); 
      } 

      Console.ReadLine(); 
     } 
    }