简体   繁体   中英

dynamic query in where clause for linq using c#

I have this below code where i filter out type which are not of "type1".

List = Details.Where(p => p.Type != Constants.Type1).ToList();

Now i have to create the where query dynamically in which i can have more clauses for filtering data.

so a modified version of above code is

List = Details.Where(p => p.Type != Constants.Type1 && p.Type != Constants.Type2 ).ToList();

Please advice how i can achieve this in c#

var ExcludedTypes = new Type[] { Constants.Type1, Constants.Type2 };
List = Details.Where(p => !ExcludedTypes.Contains(p.Type)).ToList();

You can just call Where multiple times (remembering that that won't affect the query you call it on; just the return value). For example:

var query = Details.Where(p => p.Type != Constants.Type1);
if (avoidType2)
{
    query = query.Where(p => p.Type != Constants.Type2);
}
List = query.ToList();

EDIT: Note that I'd use this approach for general purpose dynamic filtering. If you always want to filter just by type, and it's just the list of valid types that varies, then I'd use George's approach.

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