根据条件动态拼接LinQ的where条件字串

var items1 = from c in customer
    where c.Id != null && (1 == 1 ? c.FirstName == "AAA" : true) && (1 == 1 ? c.LastName == "BBB" : true)
     select c;

List<Customer> qwe11 = items1.ToList();

如果条件不多,可以直接这样写。

 

也可以用Lambda:

var items = customer.Where(m => m.Id != null);

if (1 == 1)
items = customer.Where(m => m.FirstName == "Johnny");

if (1 == 1)
items = customer.Where(m => m.LastName == "Doe");
List<Customer> qwe = items.ToList();

 

注意,这里只会查询一次,不会造成性能浪费。

posted @ 2016-08-13 11:06  好人卡收藏家  阅读(2282)  评论(1编辑  收藏  举报