如何在C#中的lambda表达式中应用多项条件以及更高的条件 [英] How to apply mulitple criteria in lambda expression in c# along with greater then criteria
问题描述
我在继续我的问题上一个问题。在我的最后一个问题中,@ p.s.w.g提供了我想要的确切解决方案。现在我想到另一种情况,假设我们需要先搜索个更大的字符,然后搜索4
,然后再做什么。
I am Continuing my question Previous Question . In my last question @p.s.w.g gives exact solution as i want . Now another situation comes into my mind that suppose we need to search greater then 4
in a condition then what will we do .
详细信息
在我最后一个问题中,我说标准将达到 1-4
,假设我们包含更多条件,并给用户一个选择 4 +
的选项,我们将返回所有数据其中卧室
大于4。在这种情况下我们将做什么。
In my last question i said the criteria will goes up to 1-4
, Suppose we include more criteria and give user a option to select 4+
and we will return all data where Bedroom
is greater then four . What we will do in this case .
假设我在我的过滤器变量 var filter = 1,4,4 +;
Suppose i got this in my filter variable var filter = "1,4,4+";
在这种情况下,我们应该向用户返回所有列表
,其中卧室为 1
或 4
或大于4
。
In this condition we should return user all Listings
where Bedrooms are either 1
or 4
or Greater then 4
.
我尝试过的事情
var bedCriteria = "1,4,4+";
bedCriteria = bedCriteria .Split(',').ToList();
bool isGreaterThenCriteria = bedCriteria.Contains("4+");
if (isGreaterThenCriteria)
{
query = query.Where(l => l.Place.Bedroom > 4);
bedCriteria.Remove("4+");
}
var minBeds = bedCriteria.Select(int.Parse);
query = query.Where(l => minBeds.Contains(l.Place.Bedroom.Value));
推荐答案
在我之前的回答中,假设您有以下内容:
Extending on my previous answer, suppose you have this:
var minBeds = "1,2,4".Split(',').Select(int.Parse);
query = query.Where(l => minBeds.Contains(l.Place.Bedroom));
您可以将其更改为...
You can change this to...
var minBedStrings = "1,4,4+".Split(',');
var has4plus = minBedStrings.Contains("4+");
var minBeds = minBedStrings.Where(x => x != "4+").Select(int.Parse);
query = query.Where(l => minBeds.Contains(l.Place.Bedroom) ||
(has4plus && l.Place.Bedroom > 4));
如果您要处理 5 +
或 6 +
...
If you want to handle something like "5+"
or "6+"
as well...
var minBedStrings = "1,4,4+".Split(',');
var nplus = minBedStrings.Where(x => x.Last() == '+')
.Select(x => (int?)int.Parse(x.Substring(0, x.Length - 1))
.OrderBy(x => x)
.FirstOrDefault();
var minBeds = minBedStrings.Where(x => x.Last() != '+')
.Select(int.Parse);
query = query.Where(l => minBeds.Contains(l.Place.Bedroom) ||
(nplus.HasValue && l.Place.Bedroom > nplus.Value));
这篇关于如何在C#中的lambda表达式中应用多项条件以及更高的条件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!