简体   繁体   中英

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:

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

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

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

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

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

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