c# - 从 List<Dictionary<DateTime, Points[]>> 转换为 Dictionary<DateTime, Points[]>

标签 c# .net-core

我有List<Dictionary<DateTime, Points[]>> taskResult从任务中生成

var taskResult = tasks.Select(t => t.Result).ToList();
var data = new Dictionary<DateTime, Points[]>();

在我的函数中我想返回 Dictionary<DateTime, Points[]> data但我不知道该怎么做。我尝试使用 foreach 但没有成功

最佳答案

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());

关于c# - 从 List<Dictionary<DateTime, Points[]>> 转换为 Dictionary<DateTime, Points[]>,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58745002/

相关文章:

C# 纪元时间到日期和时区转换

c# - docker : "npm not found"

c# - 使用 .NET Core 在 Linux 中通过 "/bin/bash"执行 .sh(bash 脚本)文件

c# - 配置选项时解析值

c# - 在特定实例上触发的委托(delegate)和事件

c# - 拆分一个字符串,使其丢失 http ://and anything after the '.'

c# - 在 Entity Framework 中使用 AddRange 批量插入

c# - 验证我的 DelegatingHandler 是否已添加到 IHttpClientBuilder

c# - .net core 中的 Web API 请求查询参数值为空

c# - 将日期传递给 oracle 函数导致无效月份