首页 > 解决方案 > 使用 c# 进行聚合分组

问题描述

我有一个看起来像的分组对象

Dictionary<(ushort id, ushort sc), Timepoint[]> timepoints

它看起来像 (1, 2) => [一些字符串时间点]

但我想将其转换为

Dictionary<ushort id, Timepoint[]>

我想聚合那个 sc 并且只有 id。我试过:

test = timepoints.GroupBy(group => group.Key.id).ToDictionary(key => key.Key, value => value);

但我没有运气。

Dictionary<ushort, IGrouping<ushort, KeyValuePair<(ushort id, ushort sc), Timepoint[]>>>

我想我错过了一些东西。

标签: c#linq

解决方案


您需要使用 aSelectMany来展平要组合在一起的数组,然后先将它们变成一个数组。

var test = timepoints
    .GroupBy(kvp => kvp.Key.id)
    .Select(grp => new { grp.Key, Values = grp.SelectMany(x => x.Value).ToArray() })
    .ToDictionary(x => x.Key, x => x.Values);

推荐阅读