2

I am creating a test repository for dependency injection and i have my test method below.

private List<object> records;

public IList<T> GetFiltered<T>(Expression<Func<T, bool>> action = null) where T : class
{
    return ((List<T>)records).Where(action).ToList();
}

I essentially want to return a filtered list of records where the "action" condition is true.

I get the error below

Error 2 Instance argument: cannot convert from 'System.Collections.Generic.List' to 'System.Linq.IQueryable'

Please help.

tereško
  • 58,060
  • 25
  • 98
  • 150
Russ
  • 549
  • 4
  • 6

2 Answers2

3

You need to use the IEnumerable<T> version of Where which expects Func<T, bool> not IQueryable<T> which takes an Expression e.g.

public IList<T> GetFiltered<T>(Func<T, bool> action = null) where T : class
{
    return ((List<T>)records).Where(action).ToList();
}

Also, List<object> can't be cast to List<T> my advice would be to make the outer class generic as well i.e.

public class MyContainer<T>
{
    private List<T> records;

    public IList<T> GetFiltered(Func<T, bool> action = null) where T : class
    {
        return records.Where(action).ToList();
    }
}
James
  • 80,725
  • 18
  • 167
  • 237
0

as i understand you can not just convert List of object to generic type you should do something like this or this

Community
  • 1
  • 1
Guru Stron
  • 102,774
  • 10
  • 95
  • 132