1

Leveraging off the Q&As dealing with looping through an object's properties (Loop Through An Objects Properties In C# and Using LINQ to loop through inner class properties in outer class collection), where you have:

  • a collection of Class1 objects (i.e. listObj1)
  • each Class1 contains properties and a collection of Class2 objects (i.e. dictObj2)

How would you:

  • Efficiently determine the properties of the inner class (Class2)
  • loop through the the properties of the inner class (Class2)
  • loop through the collection of Class1 objects (listObj1) selecting all instances of the the Class2 property
  • output the collection of Class2 property (e.g. the first iteration would return a collection of MeasurementA, one from each Class1 object).
  • and group the collection by Class1.PropertyA and Class1.PropertyB

Please find below a rough map of the classes involved.

I have been trying to use a LINQ query without success. The answer provided by Konrad Kokosa is most of the way there. Any ideas or guidance would be greatly appreciated.

class MainClass {
  List<Class1> listObj1
}

class Class1 {
  // a number of fields including...
  int PropertyA { get; set; }
  int PropertyB { get; set; }
  Dictionary<int, Class2> dictObj2 { get; set; }
}

class Class2 {
  // a number of fields all of type double...
  double MeasurementA { get; set; }
  double MeasurementB { get; set; }
  double MeasurementC { get; set; }
}
Community
  • 1
  • 1
shansen
  • 265
  • 4
  • 14

1 Answers1

0

Just Loop:

foreach(var cls1 in listObj1)
{
    int tempA = cls1.PropertyA;
    foreach(var cls2 in cls1.dictObj2)
    {
         double tempB = cls2.MeasurementB;
    }
}

Filtered/Efficient Loop:

foreach(var cls1 in listObj1.Where(c1=> c1.PropertyA > 5 && c1.PropertyB > 3))
{
    int tempA = cls1.PropertyA;
    foreach(var cls2 in cls1.dictObj2.Where(c2=> c2.MeasurementA >= 10))
    {
         double tempB = cls2.MeasurementB;
    }
}
parveen
  • 1,939
  • 1
  • 17
  • 33