0

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

3 Answers3

0

You can convert your cond to an array and then check if it Contains() the list item:

var cond = new[] { "One", "Two", "Three" };
var list2 = list1.FindAll(n => cond.Contains(n));

This will get you a list of all the items that meet the condition. If you only care about the count, you may use:

int count = list1.Count(n => cond.Contains(n));
Console.Writeline(count);
0

If you need count, you can use Count LINQ method with Contains inside:

var cond = "One,Two,Three";
var conditions = cond.Split(',').ToArray();

var count = list1.Count(w => conditions.Contains(w));

Console.Writeline(count);
ingvar
  • 4,169
  • 4
  • 16
  • 29
0

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

akaBase
  • 2,178
  • 1
  • 18
  • 31