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

Tom*_*Tom 3 c# linq lambda dictionary

我似乎找不到我要找的答案.希望有人在这里可以提供帮助.

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

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

    // Other properties not needed
}
Run Code Online (Sandbox Code Playgroud)

可以存在多个ProcessSettings.我将数据拉入List.可以将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
Run Code Online (Sandbox Code Playgroud)

我最初使用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();
Run Code Online (Sandbox Code Playgroud)

这现在给我一个只包含processId和taskId的列表.我发现这里的一些逻辑引导我朝着正确的方向前进,但这并不是我所需要的.这是什么:

Dictionary<string, List<string> = baseSettings.GroupBy(x => x.ProcessStr).ToDictionary(x => x.Key, x => x.ToList());
Run Code Online (Sandbox Code Playgroud)

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

"无法将源类型转换 System.Collections.Generic.Dictionary<string,System.Generic.List{ProcessStr:string, TaskStr:string}>>为目标类型 System.Collections.Generic.Dictionary<string,System.Collections.Generic.List<string>>

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

Tim*_*ter 9

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

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