我似乎无法找到我正在寻找的答案。希望这里有人可以提供帮助。
我有一个包含某些进程的设置信息的类。每个类都有一个 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 typeSystem.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/