如何使用linq动态过滤内存列表?

时间:2011-09-18 15:57:29

标签: c# linq linq-to-objects

想知道动态过滤内存列表的最佳方法是什么。

假设我有内存列表,我需要编写一个根据条件过滤内存列表的查找。 显然,如果值为null或为空,请使用它。 你如何构建谓词。我查看了谓词构建器,但不确定如何使用它。

见下面的代码

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

有什么建议吗? 感谢

1 个答案:

答案 0 :(得分:1)

当然,您只需使用Where

 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))
     {
         results = results.Where(c => c.Surname == criteria.Surname);
     }
     if (criteria.StartDate.HasValue && criteria.EndDate.HasValue)
     {
         DateTime start = criteria.StartDate.Value;
         DateTime end = criteria.EndDate.Value;
         results = results.Where(c => c.DateOfBirth != null &&
                                      c.DateOfBirth.Value >= start &&
                                      c.DateOfBirth.Value < end);
     }

     return results;
}

编辑:如果您愿意,可以使用DateTime?的提升操作符:

 if (criteria.StartDate.HasValue && criteria.EndDate.HasValue)
 {
     results = results.Where(c => c.DateOfBirth != null &&
                                  c.DateOfBirth >= criteria.StartDate &&
                                  c.DateOfBirth < criteria.EndDate);
 }