How to call the expression <Func <Entity, bool >> for a collection

I have an interface that defines a repository from a repository template:

interface IRepository { List<Customer> GetAllCustomers(Expression<Func<Customer, bool>> expression); } 

I implemented it against the Entity Framework:

 class EntityFrameworkRepository { public List<Customer> GetAllCustomers(Expression<Func<Customer, bool>> expression) { return DBContext.Customers.Where(expression).ToList(); } } 

This seems to work well, it allows me to do something like:

 var customers = entityFrameworkRepository.Where( customer => String.IsNullOrEmpty(customer.PhoneNumber) ); 

Now I would like to have an InMemoryRepository for testing and demo purposes. I tried to create one of them:

 class InMemoryRepository { Dictionary<int, Customer> Customers {get; set;} = new Dictionary<int, Customer>(); public List<Customer> GetAllCustomers(Expression<Func<Customer, bool>> expression) { //what do I put here? } } 

As you can see in the above code, I don’t understand what to do to implement InMemoryRepository.GetAllCustomers . What should I do to filter Clients by the provided expression and return results?

I tried:

 return Customers.Where(expression)); 

But obviously, it expects Func<KeyValuePair<int, Customer>, bool> , so I get a compilation error:

Error CS1929 "Dictionary" does not contain a definition of "Where" and the best overload method "Queryable.Where (IQueryable, Expression>)" requires a receiver of type "IQueryable" DataAccess.InMemory

+7
c # linq func iqueryable
source share
2 answers

Give it a try . AsQueryable () Method :

 return Customers.Values.AsQueryable().Where(expression); 
+8
source share

Example

 Expression<Func<Products, bool>> expresionFinal = p => p.Active; if (mydate.HasValue) { Expression<Func<Products, bool>> expresionDate = p => (EntityFunctions.TruncateTime(c.CreatedDate) <= mydate); expresionFinal = PredicateBuilder.And(expresionFinal, expresionDate ); } IQueryable<T> query = dbSet; query = query.Where(expresionFinal); 
-one
source share

All Articles