我从任务中生成了List<Dictionary<DateTime, Points[]>> taskResult
var taskResult = tasks.Select(t => t.Result).ToList();
var data = new Dictionary<DateTime, Points[]>();在我的函数中,我想返回Dictionary<DateTime, Points[]> data,但是我想不出怎么做。我试着用foreach,但没有运气。
发布于 2019-11-07 08:56:36
Enumerable.SelectMany扩展方法是作业的正确工具,它将多个集合组合成一个集合。字典是键值对的集合.
var combined = dictionaries
.SelectMany(dictionary => dictionary.Select(pair => pair))
.GroupBy(pair => pair.Key)
.ToDictionary(
group => group.Key,
group => group.SelectMany(pair => pair.Value).ToArray());如果原始字典包含重复的日期,上述方法将合并相同日期的点。
因为Dictionary实现了IEnumerable,所以可以在SelectMany的第一次调用中删除.Select。
.GroupBy的替代方法是.ToLookup方法,它可以在每个键中有多个值。
var combined = dictionaries
.SelectMany(dictionary => dictionary)
.ToLookup(pair => pair.Key, pair.Value)
.ToDictionary(
lookup => lookup.Key,
lookup => lookup.SelectMany(points => points).ToArray());https://stackoverflow.com/questions/58745002
复制相似问题