how to exclude items from List<RegistryPathData>

Viewed 67

I have a string array and a list and data is like below,

string[] str = new string[2] { "Prod1", "Prod2" };
        List<RegistryPathData> data = new List<RegistryPathData>
        {
            new RegistryPathData{AppName="test1", RegPath="Prod1|Version"},
            new RegistryPathData{AppName="test2", RegPath="Prod2|Version"},
            new RegistryPathData{AppName="test3", RegPath="Prod3|Version"},
            new RegistryPathData{AppName="test4", RegPath="Prod4|Version"},
            new RegistryPathData{AppName="test5", RegPath="Prod5|Version"},
        };

Now I want to exclude items from List<RegistryPathData> which is NOT matching with string array (prod1 & prod2). Need to exclude below 2, how to do this?

new RegistryPathData{AppName="test1", RegPath="Prod1|Version"},
        new RegistryPathData{AppName="test2", RegPath="Prod2|Version"},
3 Answers

Use List.RemoveAll() function like this.

data.RemoveAll(d => str.Contains(d.RegPath.Split('|')[0]));

You can use the LINQ .Where() method to filter a sequence of values based on a predicate.

data.Where(d => !str.Contains(d.RegPath.Split('|')[0]));

This means filter out the items in the list where the string up to the first pipe character is not contained in the str array.

Use the Where method from LINQ and then check if any of the strings inside the str array match with the RegPath of the current object. Like this:

List<RegistryPathData> dataOnlyProd1And2 = data
    .Where(rpd => str.Any(s => rpd.RegPath.StartsWith(s)))
    .ToList();
Related