Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to replace nested loops with LINQ - in a clean, manageable manner

Tags:

c#

loops

linq

Codewise, what it the cleanest way to do this using linq? Below, I have a crude example where I want to find a matching class instance based on name.

class item
{
   string name {get;set;}
   int identifier {get;set;}
}

void DoSomething()
{
  List<item> List1 = GetSampleItems();
  List<item> List2 = GetOtherSampleItems();

  for(int a=0;a<List1.count;a++)
  {
     for(int b=0;b<List2.count;b++)
     {
         if(List1[a].identifier == List2[b].identifier)
         { 
            List1[a].name = List2[b].name;
         }
     }
  }
}
like image 824
Patrick Schomburg Avatar asked Jan 27 '15 16:01

Patrick Schomburg


1 Answers

Linq is for querying, not updating, so you'll still need to loop through the results to make the changes, but you can join to match up the two lists like so:

var query = from l1 in List1
            join l2 in List2
                on l1.identifier equals l2.identifier 
            select new {l1, l2};

Now loop through the query to update the l1 items:

foreach(var item in query)
    item.l1.name = item.l2.name;

As a side note, there's nothing wrong with the way you're doing it (other than you could break out of the inner loop if a match is found). If you understand how it works and the performance is acceptable, there's no compelling reason to change it.

like image 58
D Stanley Avatar answered Sep 28 '22 01:09

D Stanley