C# Linq 或 Lambda 从类中获取 Dictionary<string, List<string>>

标签 c# linq dictionary lambda

我似乎无法找到我正在寻找的答案。希望这里有人可以提供帮助。

我有一个包含某些进程的设置信息的类。每个类都有一个 processId、taskId 和我当前逻辑不需要的各种其他信息。

public class ProcessSetting
{
    public int ProcessId { get; set; }
    public int TaskId { get; set; }

    // Other properties not needed
}

可以存在多个 ProcessSettings。我正在将数据拉入列表。一个 processId 可以与多个 TaskId 相关联。例如:

ProcessId: 1, TaskId: 1
ProcessId: 1, TaskId: 1
ProcessId: 1, TaskId: 2
ProcessId: 1, TaskId: 3
ProcessId: 2, TaskId: 3
ProcessId: 2, TaskId: 4
ProcessId: 3, TaskId: 1

我最初使用 linq 只是从现有枚举中收集我需要的值:(在最后使用 distinct 以避免拉入 ProcessId 1 和 TaskId 1 的多个记录集)

var baseSettings = (from setting in processSettings
                    select new
                              {
                                  ProcessStr = ((ProcessEnum)setting.ProcessId).ToString(),
                                  TaskStr = ((TaskEnum)setting.TaskId).ToString()
                              }).Distinct();

这现在为我提供了一个仅包含 processId 和 taskId 的列表。我在这里找到了一些引导我走向正确方向的逻辑,但这并不是我所需要的。这是什么:

Dictionary<string, List<string> = baseSettings.GroupBy(x => x.ProcessStr).ToDictionary(x => x.Key, x => x.ToList());

但是,这是不正确的。我收到一个错误:

"Cannot convert source type System.Collections.Generic.Dictionary<string,System.Generic.List{ProcessStr:string, TaskStr:string}>> to target type System.Collections.Generic.Dictionary<string,System.Collections.Generic.List<string>>

我不想要值为 {ProcessStr, TaskStr} 的 Key。谁能指出我正确的方向?

最佳答案

您必须先选择匿名类型的字符串属性,而不是 x.ToList:

Dictionary<string, List<string>> procTasks = baseSettings
    .GroupBy(x => x.ProcessStr)
    .ToDictionary(g => g.Key, g => g.Select(x => x.TaskStr).ToList());

关于C# Linq 或 Lambda 从类中获取 Dictionary<string, List<string>>,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18640141/

相关文章:

c# - 哪种方式获取满足条件的收藏品索引更好?

python - 如何在 python 中使用 OrderedDict 将值列表分配给键

c# - 多次使用时存储 O(1) 哈希查找的结果是一种好习惯吗?

c# - 已部署代码超时,但在调试期间不会超时

C# SQL 如果查询返回任何行计数

javascript - PdfSharp - 在 PDF 文档中注入(inject)的 Javascript 在 Firefox 中不起作用

c# - 为什么 Enumerable.All 对空序列返回 true?

c# - VS2012EXPRESS Ado.Net SQLite 缺少 DLL 问题

c# - 将 Func 传递给 Where 将返回类型从 IQueryable 更改为 IEnumerable

python - 检查字典键是否在字典列表(元组)中