Reputation: 3640
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:
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.
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:
var people = db.People.Where(x=>x.Country == "USA" || x.Country == "UK")
Thanks
Upvotes: 1
Views: 972
Reputation: 91
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));
Upvotes: 0
Reputation: 28272
PredicateBuilder
is the right answer. 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
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
Upvotes: 1
Reputation: 125620
You should use 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);
Upvotes: 5