gpt4 book ai didi

c# - 如何循环 Dictionary, Dictionary>?

转载 作者:太空宇宙 更新时间:2023-11-03 12:13:42 25 4
gpt4 key购买 nike

类(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 + "\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

关于c# - 如何循环 Dictionary<IEnumerable<string>, Dictionary<IEnumerable<decimal>>?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50814010/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com