如何循环字典<IEnumerable<string>,字典<IEnumerable<decimal>>?



class:

class myClass
{
public int processId { get; set; }
public string measurement { get; set; }
public decimal measurementValue { get; set; }
public string otherText { get; set; }
}

法典:

List<myClass> myClasses = new List<myClass> {
new myClass { processId=1, measurement="height", measurementValue=10,otherText="312312" },
new myClass { processId=1, measurement="length", measurementValue=11 ,otherText="312312"},
new myClass { processId=1, measurement="width", measurementValue=12 ,otherText="312312"},
new myClass { processId=2, measurement="height", measurementValue=20 ,otherText="312312"},
new myClass { processId=2, measurement="length", measurementValue=21 ,otherText="312312"},
new myClass { processId=2, measurement="width", measurementValue=22 ,otherText="312312"}
};
var groups = myClasses
.GroupBy(o => o.processId)
.ToDictionary(g => g.Select(x => x.measurement), g => g.Select(x => x.measurementValue));

groupsDictionary<IEnumerable<string>, Dictionary<IEnumerable<decimal>>

如何对所有键和值进行分组循环?我没想通。

foreach(var group in groups)
{
//????
}

对象groups结果对我来说看起来不合逻辑。这个字典使它很容易循环,而且似乎也更合乎逻辑:

var groups = myClasses
.GroupBy(o => o.processId)
.ToDictionary(g => g.Key, g => g.Select(x => new {Measurement = x.measurement, Value = x.measurementValue}));

然后循环并记录组:

foreach (var item in groups)
{
Debug.WriteLine($"Key: {item.Key}, Value: {"t" + string.Join(Environment.NewLine + "tttt", item.Value.Select(i => $"{nameof(i.Measurement)}:{i.Measurement},{nameof(i.Value)}:{i.Value}"))}");
}

将产生结果:

Key: 1, Value:  Measurement:height,Value:10
Measurement:length,Value:11
Measurement:width,Value:12 
Key: 2, Value:  Measurement:height,Value:20
Measurement:length,Value:21
Measurement:width,Value:22

最新更新