Search code examples
c#linq

Get the List Items which are Not in the string value


I am looking for a way to find out the items in the List<> which are not in the string value. I have a list<> of items as shown below :

            List<DoorDetails> ListDoorData = new List<DoorDetails>();

            DoorDetails dm = new DoorDetails();
            dm.door_id = 1;
            dm.brand = "BM";
            dm.buying_group = "Silly USA";
            dm.setting_name = "Settings1";
            dm.datamodel = 13;
            dm.tracking_weeks = 1;

            DoorDetails dm1 = new DoorDetails();
            dm1.door_id = 2;
            dm1.brand = "NB";
            dm1.buying_group = "John USA";
            dm1.setting_name = "Settings2";
            dm1.datamodel = 16;
            dm1.tracking_weeks = 14;

            DoorDetails dm11 = new DoorDetails();
            dm11.door_id = 3; ;
            dm11.brand = "JA";
            dm11.buying_group = "Mathew UK";
            dm11.setting_name = "Settings3";
            dm11.datamodel = 17;
            dm11.tracking_weeks = 45;

            ListDoorData.Add(dm);
            ListDoorData.Add(dm1);
            ListDoorData.Add(dm11); 

I have a string which has a value like as shown below:

           string filterstr = "NB|JA";

I want to get the "brand" of all items which are not in the "filterstr". That means, below is the object whose "brand" property is not "NB" and "JA",

            DoorDetails dm = new DoorDetails();
            dm.door_id = 1;
            dm.brand = "BM";
            dm.buying_group = "Silly USA";
            dm.setting_name = "Settings1";
            dm.datamodel = 13;
            dm.tracking_weeks = 1;

(Sometimes the variable "filterstr" contains more values like)

            NB|JA|WS|AM

I have tried the below code....but it is not getting the exact result.

          for (int i = 0; i < ListDoorData.Count(); i++)
            {
               if (!FilterStr.Contains(ListDoorData[i].GetType().GetProperty(FilterOrder)?.GetValue(ListDoorData[i])?.ToString()))
                {
                    ListDoorData.Remove(ListDoorData[i]);
                }
            }

where "FilterOrder" can be the "DoorDetails" class property like "brand", "buying_group" or "setting_name", etc

Please help me to get the List<> of Items which are not in the string value ??? Thanks.


Solution

  • First you need to split your filter items, then you can use Linq's Contains

    string[] filterItems = filterstr.Split('|');
    var filteredData = ListDoorData
        .Where(d => !filterItems.Contains(d.brand));
    

    If you want to filter the original list, you could either create a new:

    ListDoorData = filteredData.ToList();
    

    or use List.RemoveAll, which i'd prefer in this case:

    ListDoorData.RemoveAll(d => filterItems.Contains(d.brand));