Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Implement a LINQ Expression parameter

Tags:

c#

linq

I am using an interface I found, which has a method that takes a LINQ expression as a parameter. How would I implement this method to use the LINQ Expression? I can see it being very useful, but dont how to write the code to use it!!

Its a repository interface.

signature is...

IQueryable<T> Get(Expression<Func<T, bool>> criteria);
like image 392
SteveCl Avatar asked Jul 09 '10 11:07

SteveCl


2 Answers

Sounds like you are looking for something like this:

List<T> myList = new List<T>();
...
public IQueryable<int> Get(Expression<Func<int, bool>> criteria)
{
    return myList.Where(criteria.Compile()).AsQueryable();
}

This passes your expression criteria to the linq-method Where. You can then call it like this:

foreach(var something in myClass.Get(o => o.someProperty == 10))
{
    ...
}

Of course, this is pretty stupid; it would be better to just implement IEnumerable<T>...

like image 153
BlueRaja - Danny Pflughoeft Avatar answered Sep 21 '22 00:09

BlueRaja - Danny Pflughoeft


IQueryable<T> has an .Where() overload that takes an Expression<Func<T>> parameter. When assuming that this is a Linq2Sql or Linq2Entities repository, something like this should work

class MyRepository
{
    ObjectContext context = // initialize somehow;


    public IQueryable<int> Get(Expression<Func<int, bool>> predicate)
    {
        return context.SomeObject.Where(predicate);
    }
}

If that's not the case, and you only have an enumerable, you can use AsQuerably() as the first step in the chain to convert it to IQuerably, giving you the option to use the expression based predicate:

public IQueryable<int> Get(Expression<Func<int, bool>> predicate)
{
    return mySimpleList.AsQuerable().Where(predicate);
}
like image 36
Sander Rijken Avatar answered Sep 22 '22 00:09

Sander Rijken