Pure.Krome
Pure.Krome

Reputation: 86997

What's the most efficient way to do these two foreach-loops?

i'm not sure this is the best way to do the following code. I'm not sold on a foreach inside another foreach. Could this be done *better** with Linq?

*I understand that better could be either
a) more performant
b) easier to read / more elegant
c) all of the above

NOTE: .NET 3.5 solutions accepted :) NOTE2: the two IList's were the results of a multi-recordset stored procedure, via Linq2Sql.

here's the make believe code:

// These two lists are the results from a IMultipleResults Linq2Sql stored procedure.
IList<Car> carList = results.GetResult<Car>().ToList();
IList<Person> people = results.GetResult<Person>().ToList();

// Associate which people own which cars.
foreach(var person in people)
{
    var cars = (from c in cars
                where c.CarId == person.CarId
                select c).ToList();

    foreach (var car in cars)
    {
        car.Person = person;    
    }
}

Cheers :)

Upvotes: 2

Views: 269

Answers (1)

Sedat Kapanoglu
Sedat Kapanoglu

Reputation: 47680

I don't think performance would be any different but if you're looking for terseness:

var q = from person in people
        join car in cars on person.CarId equals car.CarId
        select new { car, person };
foreach(var o in q)
{
  o.car.Person = o.person; 
}

Edit: After Jon's hint on this version being faster I got curious and profiled both functions. This version seems twice as fast which is amazing. I checked the disassembly. The overhead of the original implementation seems to come from new enumerators getting created for both outer and inner loop, causing P times new/dispose overhead.

For this code only one Enumerator is created which I think is the magic of "Join" function. I didn't examine how it works though.

Upvotes: 6

Related Questions