簡體   English   中英

如何使用linq動態過濾內存中的列表?

[英]How do you filter an in memory list dynamically using 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; } 
}

有什么建議么? 謝謝

當然,您只需使用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?使用解除運算符DateTime? 如果您想在這里:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM