Given data:
MainClass mainClass = new MainClass();
mainClass.listObj1 = new List<Class1>()
{
new Class1() {
dictObj2 = new Dictionary<int,Class2>() {
{ 1, new Class2() { MeasurementA = 2.0, MeasurementB = 3.0, MeasurementC = 4.0 }},
{ 2, new Class2() { MeasurementA = 5.0, MeasurementB = 6.0, MeasurementC = 7.0 }}
}
}
};
you can write with LINQ:
var fields = typeof(Class2)
// Get Properties of the ClassB
.GetProperties(BindingFlags.Public | BindingFlags.Instance)
// Map each PropertyInfo into collection of its values from c1.dictObj2
.SelectMany(pi => mainClass.listObj1
.SelectMany(c1 => c1.dictObj2)
.Select(p => new
{
Property = pi.Name,
Value = pi.GetValue(p.Value)
}))
// Group data with respect to the PropertyName
.GroupBy(x => x.Property, x => x.Value)
// And create proper dictionary
.ToDictionary(x => x.Key, x => x.ToList());
and now you have a Dictionary
with keys of ClassB
property names and values as List
of those properties values.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…