Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Linq to object dynamic query is it possible?

Tags:

c#

linq

Wondering if it's possible to create a dynamic linq query using linq to objects.

I have a screen where a user can filter on multiple things. I Need to build an in memory filtering NOT using a database

So lets suppose I have a list of customers in memory and I would like to filter based on some multiselection.

I thought a method that I could pass a predicate would do the trick ,but obviously not.

How can I do it?

eg

public class Biz
{
    public List<Customer> GetAllByName(string name)
    {
        return Repository.Find(x=> x.Name == name);
    }
}

public class Repository
{
    private List<Customer> internalCustomerList = GetAllCustomers();

    public IEnumerable<Customer> Find(Expression<Func<T, bool>> predicate)
    {
        //How do I make below work in linq to object
        return  internalCustomerList.Where(predicate);//error here
    }
}
like image 296
user9969 Avatar asked Dec 27 '22 14:12

user9969


1 Answers

An alternate approach would be to pass a string filter rather than a predicate. The Dynamic LINQ Library makes this possible.

public IEnumerable<Customer> Find(string filter)
{
    //filter would be something like "Age >= 20"
    return internalCustomerList.Where(filter);
}
like image 77
codeConcussion Avatar answered Feb 08 '23 08:02

codeConcussion