如何循环Dictionary <ienumerable <string>,Dictionary <ienumerable <decimal>&gt;?

时间:2018-06-12 09:42:08

标签: c# dictionary .net-4.0

类:

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)
{
    //????
}

1 个答案:

答案 0 :(得分:1)

结果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 + "\t\t\t\t", 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