簡體   English   中英

自定義對象列表-與SQL'Like'子句相似的Linq過濾

[英]Custom Object List - Linq Filtering Similar to SQL 'Like' clause

我使用的數據表效果很好,但是我決定將其轉換為自定義對象列表,以保留一些系統資源。

在我的客戶清單中,我有帶有郵政編碼的對象:

B1 7NY,B2 8JK,B1 XLS,B9 2BY,

BW7 1NJ,BF9 3NJ,BJ4 2NP,BW8 5DO,

現在,用戶可以在我的列表框中選擇:B,BW,BF,BJ,

因此,我需要一個查詢,當用戶在列表框中選擇“ B”時,我想刪除所有如上所述的B1-B9郵政編碼。

如果用戶選擇“ BW”,我想刪除所有BW郵政編碼。

customerList.Where(c => c.Postcode.StartsWith(postcodeID.ToString()));

當郵政編碼id = BL時,此方法會很好用,但是當郵政編碼2nd char為數字時該怎么辦。 B1-B9。 如何選擇郵政編碼類似於b1-b9的所有對象?

   if (char.IsDigit(postcodeID.ToString()[1]))
   {
       CustList.RemoveAll(c => c.Postcode[0] == postcodeID[0] &&
                                                    char.IsDigit(c.Postcode[1]));
   }
   else
   {
       CustList.RemoveAll(c => c.Postcode.StartsWith(postcodeID.ToString()));
   }

您可以檢查第二個char是否為數字,並根據該數字構造查詢:

if(char.IsDigit(postcodeID.ToString()[1]))
{
    query = customerList.Where(c => c.Postcode[0] == 'B' &&
                                    char.IsDigit(c.Postcode[1]));
}
else 
{
    query = customerList.Where(c => c.Postcode.StartsWith("BL"));
}

暫無
暫無

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

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