gpt4 book ai didi

c# - 如何针对集合调用 Expression>

转载 作者:可可西里 更新时间:2023-11-01 08:44:10 25 4
gpt4 key购买 nike

我有一个从存储库模式定义存储库的接口(interface):

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

我已经在 Entity Framework 上实现了它:

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

这似乎工作得很好,它允许我做类似的事情:

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

现在我想要一个用于测试和演示目的的 InMemoryRepository。我试图创建一个:

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?
}
}

正如您在上面的代码中看到的,我不知道要为 InMemoryRepository.GetAllCustomers 做什么执行。我应该怎么做才能通过提供的表达式过滤客户并返回结果?

我试过:

return Customers.Where(expression));

但显然它期待一个 Func<KeyValuePair<int, Customer>, bool>所以我得到一个编译错误:

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

最佳答案

尝试 .AsQueryable()方法:

return Customers.Values.AsQueryable().Where(expression);

关于c# - 如何针对集合调用 Expression<Func<Entity, bool>>,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32753012/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com