2014-10-10 20 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(); 
     } 
    }