以应用多张标准中lambda表达式在c#(To apply mulitple criteria in

2019-10-18 08:00发布

I have two main tables Listings and Place . In listing table there is a field PlaceId which referes to a Place entity/row/object . I want to query on both tables so that i get both of them like this .

 var query = context.Listings
       .Include("Place")
       .Where(l => l.Place.TypeId == Type.Ro)
       .OrderBy(l => l.Id).ToList();

after this now i want to put some filter on this query , here is the condition .

i got only a string like this var filter = "1,2,4"; . Now i want to filter on listing to gett all these listing where bedroom is equal to 1 OR 2 OR 4 .

What i have done

 string minBeds = "1,2,4";

 foreach (var item in minBeds.Split(','))
 {
      int minBed = int.Parse(item);
      query = query.Where(l=>l.Place.Bedroom == minBed).ToList();
 }

But doing this is giving me Zero result.

Answer 1:

与你过滤的方式的问题。 第一遍后,你过滤掉,除非一切Bedroom == 1 ,在第二次你过滤掉,除非一切Bedroom == 2 ,但因为在列表中唯一的项目有Bedroom == 1 ,你不会有结果集东西。

解决的办法是使用传统的C# || 运营商:

query = query.Where(l => l.Place.Bedroom == "1" || 
                         l.Place.Bedroom == "2" || 
                         l.Place.Bedroom == "4");

或者,如果你想成为更灵活,可以使用Contains方法:

string[] minBeds = "1,2,4".Split(',');
query = query.Where(l => minBeds.Contains(l.Place.Bedroom));

注意:如果Bedroom是一个整数,你需要输入转换成合适的类型第一:

var minBeds = "1,2,4".Split(',').Select(int.Parse);
query = query.Where(l => minBeds.Contains(l.Place.Bedroom));

另外请注意,我已经消除了ToList这里。 除非你需要通过指数从结果集合访问项目,并添加/删除项目,这是最有可能只是浪费资源。 通常你可以依靠的LINQ的原生懒惰延迟处理查询,直到你真正需要的结果。



文章来源: To apply mulitple criteria in lambda expression in c#