我有一个看起来像分组的对象
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[]>>>
我想我缺少什么。
答案 0 :(得分:3)
您需要使用SelectMany
来整理要分组在一起的阵列,然后将它们首先转换为一个阵列。
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);
答案 1 :(得分:1)
@juharr答案的扩展和测试版本;
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);
这是您可以试用的整个测试控制台应用程序:
static void Main(string[] args)
{
Dictionary<(ushort id, ushort sc), Timepoint[]> timepoints = new Dictionary<(ushort id, ushort sc), Timepoint[]>();
timepoints.Add((1, 1), new Timepoint[] { new Timepoint(1, "1,1,1"), new Timepoint(1, "1,1,2"), new Timepoint(1, "1,1,3") });
timepoints.Add((1, 2), new Timepoint[] { new Timepoint(1, "1,2,1"), new Timepoint(1, "1,2,2"), new Timepoint(1, "1,2,3") });
timepoints.Add((2, 1), new Timepoint[] { new Timepoint(1, "2,1,1"), new Timepoint(1, "2,1,2"), new Timepoint(1, "2,1,3") });
timepoints.Add((2, 2), new Timepoint[] { new Timepoint(1, "2,2,1"), new Timepoint(1, "2,2,2"), new Timepoint(1, "2,2,3") });
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);
}
class Timepoint
{
public Timepoint(int id, string name)
{
this.Id = id;
this.Name = name;
}
public int Id { get; set; }
public string Name { get; set; }
}