简体   繁体   English

基于条件值构建linq查询

[英]Build a linq query based on conditional values

I have a large record set of people and each of those people are in a country. 我有很多人,每个人都在一个国家里。

I cam retrieve all people in Australia using Entity Framework with the following: 我可以使用Entity Framework通过以下方式检索澳大利亚的所有人:

var people = db.People.Where(x=>x.Country == "Australia")

What I'm not sure how to do is to retrieve people that are in Country X or Country Y based on a set of Boolean values. 我不确定该怎么做,是根据一组布尔值检索X国家或Y国家中的人。

Ie: 即:

bool USA = true;
bool Australia = false;
bool UK = true;
bool China = false;

How do I build a linq query that in this case would give me: 我如何建立一个linq查询,在这种情况下会给我:

var people = db.People.Where(x=>x.Country == "USA" || x.Country == "UK")

Thanks 谢谢

You should use PredicateBuilder : 您应该使用PredicateBuilder

var predicate = PredicateBuilder.False<People>();

if (USA)
    predicate = predicate.Or(p => p.Country == "USA");
if (Australia)
    predicate = predicate.Or(p => p.Country == "Australia");

// ...

var people = dp.People.Where(predicate);

PredicateBuilder is the right answer. PredicateBuilder是正确的答案。 As an alternative, you could do something like: 或者,您可以执行以下操作:

var countries = new List<string>();

if(USA) countries.Add("USA");
if(Australia) countries.Add("Australia");
if(UK) countries.Add("UK");

// ...

var people = dp.People.Where(x => countries.Contains(x.Country));

This would be translated to a WHERE IN SQL clause 这将被转换为WHERE IN SQL子句

Update 更新资料

As the comments point out, in a Linq-To-Entities (or Linq-To-SQL) scenario, it doesn't matter, but if you plan to use this for Linq-To-Objects, it'd be wiser to use a HashSet<string> instead of a List<string> for performance reasons 正如评论所指出的那样,在Linq-To-Entities(或Linq-To-SQL)方案中,这没关系,但是如果您打算将其用于Linq-To-Objects,则使用它会更明智。出于性能原因,使用HashSet<string>代替List<string>

Try this: 尝试这个:

//You can add, remove or change filters
var tempDictionary = new Dictionary<string, bool>
{
    {"USA", true},
    {"Australia", false},
    {"UK", true},
    {"China", false},
};
//Get relevant filters
var tempFilter = tempDictionary
                 .Where(item => item.Value)
                 .Select(item => item.Key)
                 .ToArray();
var tempPeople = db
                 .People
                 .Where(x => tempFilter.Contains(x.Country));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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