-1

I couldn't really figure out how to word the question so I will just explain what I am trying to do in a simpler or faster way.

I have a class called GearBoxInfo that is used for storing the various properties of a gearbox. Inside GearBoxInfo is a field called GearSets which is type List<GearSet>. The GearSet class has a field called Gears which is of type List<Gear>.

I am trying to loop through each Gear inside the GearBoxInfo, but to do that I need to also loop through each GearSet inside the GearBoxInfo, like this:

for (var i = 0; i < gearBoxInfo.GearSets.Count; i++) {
    for (var j = 0; j < gearBoxInfo.GearSets[i].Gears.Count; i++) {
        Gear g = gearBoxInfo.GearSets[i].Gears[j];
        /* ... */
    }
}

I am wondering if there is a more efficient way to do this (e.g. some LINQ function), as nested loops may take a long time. In the future, I may need to iterate through a field of Gear, for example, which would require another nested loop.

E-Bat
  • 4,792
  • 1
  • 33
  • 58
kjsmita6
  • 458
  • 1
  • 6
  • 21

2 Answers2

0

SelectMany is exactly what you are after, it flattens collections into one sequence:

var gears = gearBoxInfo.GearSets.SelectMany(gs=>gs.Gears);

More examples here

E-Bat
  • 4,792
  • 1
  • 33
  • 58
-1

I'm not sure why you need to loop. Do you need to iterate through each gear for a specific reason or are you looking for a specific gear? If you're looking for a specific gear you could use the .Find() or .First() methods.

for (var i = 0; i < gearBoxInfo.GearSets.Count; i++) {
    Gear g = gearBoxInfo.GearSets.First(f => f == "XYZ123");
    /* ... */
}
FrankJames
  • 100
  • 1