views:

3615

answers:

4

Is there a pattern using Linq to dynamically create a filter?

I have the need to create custom filtering on a list, in the past I would just dynamically create the SQL...it doesn't seem like this is possible with Linq.

+6  A: 
Geoff
+1  A: 

something like this?

var myList = new List<string> { "a","b","c" };
var items = from item in db.Items
            where myList.Contains(item.Name)
            select item;

that would create a sql statement like

SELECT * FROM Items [t0] where Name IN ('a','b','c')
Darren Kopp
+2  A: 

Dynamic Linq is one way to go.

It may be overkill for your scenario. Consider:

IQueryable<Customer> query = db.Customers;

if (searchingByName)
{
  query = query.Where(c => c.Name.StartsWith(someletters));
}
if (searchingById)
{
  query = query.Where(c => c.Id == Id);
}
if (searchingByDonuts)
{
  query = query.Where(c => c.Donuts.Any(d => !d.IsEaten));
}
query = query.OrderBy(c => c.Name);
List<Customer> = query.Take(10).ToList();
David B