如何使用 linq 动态过滤内存列表?
想知道动态过滤内存列表的最佳方法是什么。
假设我有内存列表,我需要编写一个查找,根据条件过滤内存列表。 显然,如果一个值为 null 或空,请使用它。 如何构建谓词。我看过 predicateBuilder 但不知道如何使用它。
请参阅下面的代码
public class CustomerService
{
private IEnumerable<Customer> customersInMemoryAlready;
public CustomerService()
{
customersInMemoryAlready = new List<Customer>();//Pretend we have fetched 200 customers here
}
public IEnumerable<Customer> Find(Criteria criteria)
{
IEnumerable<Customer> results = GetInMemoryCustomers();
//Now filter based on criteria How would you do it
if(!string.IsNullOrEmpty(criteria.Surname))
{
//?
}
if (!criteria.StartDate.HasValue && !criteria.EndDate.HasValue)
{
//?Get all dateOfBirth between StartDate and EnDate
}
return results;
}
private IEnumerable<Customer> GetInMemoryCustomers()
{
return customersInMemoryAlready;
}
}
public class Customer
{
public string Firstname { get; set; }
public string Surname { get; set; }
public DateTime?DateOfBirth { get; set; }
public string City { get; set; }
}
public class Criteria
{
public string Firstname { get; set; }
public string Surname { get; set; }
public DateTime?StartDate { get; set; }
public DateTime? EndDate { get; set; }
public string City { get; set; }
}
有什么建议吗? 谢谢
Wondering what is the best approach to filter an in memory list dynamically.
Lets suppose I have in memory List and I need to write a find that filters the in memoryList based on the criteria.
Obviously if a value is null or empty do use it.
How do you build the predicate. I have looked at the predicateBuilder but not sure how to use it.
See code below
public class CustomerService
{
private IEnumerable<Customer> customersInMemoryAlready;
public CustomerService()
{
customersInMemoryAlready = new List<Customer>();//Pretend we have fetched 200 customers here
}
public IEnumerable<Customer> Find(Criteria criteria)
{
IEnumerable<Customer> results = GetInMemoryCustomers();
//Now filter based on criteria How would you do it
if(!string.IsNullOrEmpty(criteria.Surname))
{
//?
}
if (!criteria.StartDate.HasValue && !criteria.EndDate.HasValue)
{
//?Get all dateOfBirth between StartDate and EnDate
}
return results;
}
private IEnumerable<Customer> GetInMemoryCustomers()
{
return customersInMemoryAlready;
}
}
public class Customer
{
public string Firstname { get; set; }
public string Surname { get; set; }
public DateTime?DateOfBirth { get; set; }
public string City { get; set; }
}
public class Criteria
{
public string Firstname { get; set; }
public string Surname { get; set; }
public DateTime?StartDate { get; set; }
public DateTime? EndDate { get; set; }
public string City { get; set; }
}
Any suggestions?
Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
当然,您只需使用
Where
:编辑:如果您愿意,您可以在
DateTime?
中使用提升的运算符:Sure, you just use
Where
:EDIT: You can use the lifted operators for
DateTime?
if you want to here: