Fraz Zaki
Fraz Zaki

Reputation: 309

how to apply where clause in generic type list in c#

i have a generic method like this

 public IList<T> Get(KendoGridFilterSort.FilterContainer filter)
    {
        List<T> list = null;
        IQueryable<T> dbQuery = _entities.Set<T>();
        list = dbQuery
        .ToList<T>();
        return list;

    }

when in inititate the class of this method with specific object i got the full list of records. but i want to pass some filter thorough parameters in this method to filter records accordingly . for this i have class name KendoGridFilterSort.FilterContainer that contain all the filter with field name, operator and values i want to use that filters with this generic method , my problem is i cannot use this statement for example

persons.Where(p => p.Name == name && p.Surname == surname).ToList();

so is there any possibility that i could apply my filter on this generic list ?

Upvotes: 0

Views: 2503

Answers (2)

Slava Utesinov
Slava Utesinov

Reputation: 13488

You should force your T class implement IEntity interface with properties, that you want to filter:

public interface IEntity
{
   string Name {get;set;}
   string Surname {get;set;}
}

public class Repository<T> where T : class, IEntity
{
    public IList<T> Get(KendoGridFilterSort.FilterContainer filter)
    {
        return _entities.Set<T>().Where(x => x.Name == filter.Name && x.Surname == filter.Surname).ToList();
    }
}

Upvotes: 1

SWilko
SWilko

Reputation: 3612

You could pass in a filter as an Expression tree as you're using IQueryable<T>

public IList<T> Get(Expression<Func<T, bool>> filter)
{
    List<T> list = null;
    IQueryable<T> dbQuery = _entities.Set<T>();
    dbQuery = dbQuery.Where(filter);
    list = dbQuery.ToList<T>();
    return list;
}

Although its unclear what KendoGridFilterSort.FilterContainer is doing

Upvotes: 0

Related Questions