-6

I have three lists

List1 < Labels > lbl and List2 < Strings > value and List3 < Strings > result

and I wanna compare both using foreach like

if (label1.text == value ) {  // value is the 2nd list name
 Label_Result.text = Result    // in third List
 Label1.font= new font("Tahoma",18);
 ListBox1.items.add(Label.text);
}

Edit ,,

I think what I need is three Lists

danblack
  • 12,130
  • 2
  • 22
  • 41
Osamah
  • 1
  • 4

2 Answers2

0

Three basic examples. The first uses a simple nested foreach:

foreach(var item1 in list1)
    foreach(var item2 in list2)
        if(item1.text == item2)
        {
            //Do your thing
        {

You could reduce nesting by using LINQ. Note that you could make this considerably fancier in LINQ (you can join lists), but I've chosen a simpelr example to show you the basic idea.

foreach(var item1 in list1)
{
    var matchesInList2 = list2.Where(item2 => item1.text == item2);
    foreach(var match in matchesInList2)
    {
        //Do your thing
    }
}

There is a simpler way to approach it:

var matches = list1.Where(item1 => list2.Contains(item1.text));
foreach(var item1 in matches)
{
        //Do your thing, e.g.:
        //var theTextValue = item1.text;
}

To explain this simpler approach: we immediately filter list1, and only keep the elements whose .text value exists in list2.
After that, it is simply a matter of looping over the found matches, you don't need to filter anymore.

Flater
  • 12,908
  • 4
  • 39
  • 62
-1

i think the best way is:

foreach(var list1item in lbl)  //List1 item
{
     foreach(var list2item in value) //List2 item
     {
       if(list1item == list2item)
       {
          //Do something
       }       
     }
}
Moonfred
  • 14
  • 3