Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you add dynamic 'where' clauses to a linq query?

Tags:

I've got a User table with a bitmask that contains the user's roles. The linq query below returns all the users whose roles include 1, 4 or 16.

var users = from u in dc.Users             where ((u.UserRolesBitmask & 1) == 1)                || ((u.UserRolesBitmask & 4) == 4)                || ((u.UserRolesBitmask & 16) == 16)             select u; 

I'd like to rewrite this into the method below to returns all the users from the given roles so I can reuse it:

private List<User> GetUsersFromRoles(uint[] UserRoles) {} 

Any pointers on how to dynamically build my query? Thanks

like image 361
Nick Avatar asked Oct 07 '08 21:10

Nick


People also ask

Can you use LINQ on dynamic?

The Dynamic LINQ library let you execute query with dynamic string and provide some utilities methods such as ParseLambda , Parse , and CreateClass .

What is LINQ dynamic?

The Dynamic LINQ library exposes a set of extension methods on IQueryable corresponding to the standard LINQ methods at Queryable, and which accept strings in a special syntax instead of expression trees.

Where LINQ is used in C#?

You can write LINQ queries in C# for SQL Server databases, XML documents, ADO.NET Datasets, and any collection of objects that supports IEnumerable or the generic IEnumerable<T> interface. LINQ support is also provided by third parties for many Web services and other database implementations.


1 Answers

You can use the PredicateBuilder class.

PredicateBuilder has been released in the LINQKit NuGet package

LINQKit is a free set of extensions for LINQ to SQL and Entity Framework power users.

like image 146
ilitirit Avatar answered Oct 23 '22 21:10

ilitirit