根据条件值构建linq查询

时间:2015-04-12 05:37:33

标签: c# linq

我有很多人记录,每个人都在一个国家。

我使用以下内容使用Entity Framework检索澳大利亚的所有人:

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

我不确定怎么做是根据一组布尔值检索国家X或国家Y的人。

即:

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

如何构建一个linq查询,在这种情况下会给我:

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

由于

3 个答案:

答案 0 :(得分:5)

您应该使用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);

答案 1 :(得分:1)

PredicateBuilder是正确的答案。作为替代方案,您可以执行以下操作:

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

这将转换为WHERE IN SQL子句

更新

正如评论所指出的那样,在Linq-To-Entities(或Linq-To-SQL)场景中,它并不重要,但是如果你计划将它用于Linq-To-Objects,那就是出于性能原因,更明智地使用HashSet<string>而不是List<string>

答案 2 :(得分:0)

试试这个:

//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));
相关问题