How to apply mulitple criteria in lambda expression in c# along with greater then criteria

纵饮孤独 提交于 2020-02-05 06:30:06

问题


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 .

Detail

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 .

Suppose i got this in my filter variable var filter = "1,4,4+";

In this condition we should return user all Listings where Bedrooms are either 1 or 4 or Greater then 4.

What I Have Tried

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));

回答1:


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));

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));



回答2:


If you keep adding different filtering options you can try to parse filter string manually and than realize your predicate logic with PredicateBuilder



来源:https://stackoverflow.com/questions/17419346/how-to-apply-mulitple-criteria-in-lambda-expression-in-c-sharp-along-with-greate

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!