Search code examples
c#listfindall

How can I improve a List.Findall() with conditionals OR based on an array?


I'm trying improve a filter to an element list that matches any elements fron another list.

So, today, the code list looks like below:

var list1 = new List<String>();
list1.Add("One");
list1.Add("Two");
list1.Add("One");
list1.Add("Two");
list1.Add("Three");
list1.Add("Four");

var newlist = list1.FindAll(l => l == "One" ||l == "Two" ).ToList();

Console.Writeline(newlist.Count);//This is the result I'm looking for.

The new requestiment is that the conditions varies depending on what is needed So I changed l == "One" ||l == "Two" to an array and code the logic as below:

The code changes I made is that base on I created var cond = "One,Two,Three";

and now the code looks :

var cond = "One,Two,Three";

var list2 = new List<String>();
foreach ( String l in cond.Split(','))
{
    list2.AddRange(list1.FindAll(n => n == l).ToList());
}
Console.Writeline(list2.Count);//This is the result I'm looking for.

this works, but the foreach loop with go for each conditional at the time.

Can the foreach loop be improved?

Thanks


Solution

  • Another way and a couple of things I noticed with your setup that could be improved.

    static void Main(string[] args)
            {
                //Rather than making a string you need to split into an array just start with one.
                string[] targetValues = { "One", "Two" };
    
                //You don't need to use Upper Case for String when creating a this list
                List<string> queryValues = new List<string>
                {
                    "One",
                    "Two",
                    "One",
                    "Two",
                    "Three",
                    "Four"
                };
    
                // Comparison done here
                List<string> results = queryValues.Where(x => targetValues.Contains(x)).ToList();
    
                // Seperating the list for the printout for easier viewing 
                Console.WriteLine(string.Join(", ", results));
            }
    

    Info on String vs string found here