Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamic LINQ on IEnumerable?

Say i need to filter a generic list with a dynamic query (List<string> l; var x = l.Where(*dynamic query*))

How would i do this using LINQ? (Currently using a row filter on a dataview)

I've seen a posting by scott g: but it appears to not work with objects that use IEnumerable (generic lists included)

Can anyone offer any ideas?

like image 274
maxp Avatar asked Jan 27 '09 23:01

maxp


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 Dynamic Linq?

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.


2 Answers

Assuming you mean a string-based query: the dynamic LINQ library will work fine; just call .AsQueryable() first:

string s = *dynamic query*
var qry = l.AsQueryable().Where(s);

This gives you an IQueryable<T> wrapper around your list, which provides access to the dynamic LINQ extension methods.

like image 95
Marc Gravell Avatar answered Oct 21 '22 20:10

Marc Gravell


You can use the FindAll() method which takes a predicate. Here is a basic example.

List<string> stringList = new List<string>(new string[]{"Smith", "Johnson", "Jordan","Doe"});

List<string> filteredStringList = stringList.FindAll(x => x == "Smith");

Also the Find method returns a single item.

There is also an example project on MSDN for executing dynamic LINQ queries on both IEnumerable and IQueryable. You can reuse the DynamicQueryable class from it. Here is the link. The project is inside the C# samples project.

like image 25
CoderGuy Avatar answered Oct 21 '22 20:10

CoderGuy