【问题标题】:How to loop Dictionary<IEnumerable<string>, Dictionary<IEnumerable<decimal>>?如何循环 Dictionary<IEnumerable<string>、Dictionary<IEnumerable<decimal>>?
【发布时间】:2018-06-12 09:42:08
【问题描述】:

类:

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&lt;IEnumerable&lt;string&gt;, Dictionary&lt;IEnumerable&lt;decimal&gt;&gt;

如何循环分组以获取所有键和值?我没弄明白。

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

【问题讨论】:

  • 您确定要将 IEnumerable 作为字典的键吗?
  • @CodeNotFound 它是由 linq 生成的
  • 因你而由Linq生成=>.ToDictionary(g =&gt; g.Select(x =&gt; x.measurement), ...)。通常我们这样做 => .ToDictionary(g =&gt; g.Key, ...

标签: c# dictionary .net-4.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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-09-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多