生成ToList()时LINQ检查字符串属性为NULL

时间:2014-10-10 08:38:27

标签: c# linq

我有这个Linq语句,如果属性不是空的

,它会成功构建一个列表
 results.AddRange(m_CTS.Entity.Where(x => x.Property.Contains(search)).ToList());

但是,如果x.property为null然后它出错,那么我想尝试将其检查为null,如果它为null,则继续构建列表。

我试过了,

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

但这也是错误,我做错了什么?

先谢谢

4 个答案:

答案 0 :(得分:7)

你应该像这样检查null

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

Where需要一个返回bool的语句,但是你的第一个表达式返回string而另一个表达式返回bool。所以它不会编译。< / p>

&&short-circuiting而起作用的原因。如果x.Property != null评估为假,则第二个表达式不会被评估,您将无法获得异常。

答案 1 :(得分:4)

x.Property.Contains(search)会返回bool,因此您的三元运营商的另一方也应该这样做:

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

或者简单地说:

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

答案 2 :(得分: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();
        }
    }

答案 3 :(得分:0)

检查

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