简体   繁体   中英

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

I am using a datatable which works great however I have decided to convert this to a custom object list to preserve some system resources.

In my Custlist I have objects with postcodes:

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

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

Now in my Listbox the user can select: B, BW, BF, BJ,

So I need a query that when the user selects 'B' in the listbox, I want to remove all of the B1-B9 postcodes as above.

If the user selects 'BW' I want to remove all of the BW postcodes.

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

This would work fine for when postcode id = BL but what about when the postcode 2nd char is numeric. B1-B9. How do I select all objects where postcode is like 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()));
   }

You can check if the second char is a digit and construct the query based on that:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM