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
Sure, you just use
Where:EDIT: You can use the lifted operators for
DateTime?if you want to here: