简体   繁体   中英

Conditional Where clause in Linq query for specific cases

I have an entity framework query which is retrieving results from a database based on a specific criteria. However, there is an instance where I want to filter results based on a condition within the where clause. I think a case statement is how I would achieve this, can anyone point me in the right direction?

So, for results returned from the OutageList, for cases where the outage type is "Live", I only want it to be included in the results if the NumberOfPeopleAffected are more than 4. For example:

 outageList.Where(o => o.FaultType == "Live" && o.NumberOfPeopleAffected > 4)

The problem is, the above code isn't sufficient because I want to return other outages too, it's just that for the case of Live outages, I only want to return them if the Number of people affected is more than 4.

Does this make sense? Is it a case statement that I need? If so what's the best way to write this in LINQ?

您可以在Where()子句中包含OR条件:

outageList.Where(o => (o.FaultType == "Live" && o.NumberOfPeopleAffected > 4) || o.FaultType != "Live");

To do what you want in linq use below.

var faultList = new[] {"Live", "SomethingElse"};

outageList.Where(o => faultList.Contains(o.FaultType) && o.NumberOfPeopleAffected > (o.FaultType == "Live" ? 4 : 0));

To be honest I would be okay with using this statement but I realize its can be hard to read.

使用此查询:

 outageList.Where(o => (o.FaultType == "Live" && o.NumberOfPeopleAffected > 4) || o.FaultType != "Live")

Because as you build up your query, the type is IQueryable, and because it will not actually hit the database (or whatever) and 'materialize' the results until you .Select or .ToList() , you might consider chaining your filters in switch / if clauses. This will effectively add a bunch or 'where' clauses to your query until you actually execute it.

eg:

if(case1)
outageList = outageList.Where(o => o.FaultType == "Live" && o.NumberOfPeopleAffected > 4)

if(case2)
outageList = outageList.Where(o => o.FaultType == "Unplanned" && o.NumberOfPeopleAffected > 0)

return outageList.Select(i => new myViewModel{
    prop1 = i.prop1,
    prop2 = i.prop2 // etc
})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM