要在C#中的lambda表达式中应用多个标准 [英] To apply mulitple criteria in lambda expression in c#
问题描述
我有两个主表列表
和放置
。在列表表中有一个字段 PlaceId
,它引用一个Place实体/行/对象。我想查询这两个表,这样我得到了他们这样的。
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 .
我只有一个这样的字符串 var filter =1,2,4;
。现在我想过滤列表gett所有这些列表,其中卧室等于1或2或4。
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 .
我做了什么
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.
推荐答案
筛选方式的问题。第一遍之后,除了 Bedroom == 1
,过滤掉第二遍的所有东西,除了卧室== 2
,但由于列表中只有 Bedroom == 1
,所以在结果集中不会有任何内容。
The problem with the way you're filtering it. After the first pass, you're filtering out everything except where Bedroom == 1
, on the second pass you're filtering out everything except where Bedroom == 2
, but since the only items in the list have Bedroom == 1
, you won't have anything in the result set.
解决方案是使用常规的C# ||
运算符:
The solution is to use the conventional C# ||
operator:
query = query.Where(l => l.Place.Bedroom == "1" ||
l.Place.Bedroom == "2" ||
l.Place.Bedroom == "4");
或者如果要更灵活,请使用 包含
方法:
Or if you want to be more flexible, use the Contains
method:
string[] minBeds = "1,2,4".Split(',');
query = query.Where(l => minBeds.Contains(l.Place.Bedroom));
请注意,如果 Bedroom
需要首先将输入转换为适当的类型:
Note if Bedroom
is an integer, you'll need to convert the input to an appropriate type first:
var minBeds = "1,2,4".Split(',').Select(int.Parse);
query = query.Where(l => minBeds.Contains(l.Place.Bedroom));
另外请注意,我已经删除了 ToList
这里。除非您需要通过索引访问项目并从结果集合中添加/删除项目,这很可能只是浪费资源。你通常可以依靠Linq的本地惰性来延迟处理,直到你真正需要结果。
Also note, I've eliminated the ToList
here. Unless you need to access items by index and add / remove items from the result collection, it's most likely just a waste of resources. You can usually rely on Linq's native laziness to delay processing to query until you really need the result.
这篇关于要在C#中的lambda表达式中应用多个标准的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!