【问题标题】:C# Linq or Lambda to get Dictionary<string, List<string>> from a classC# Linq 或 Lambda 从类中获取 Dictionary<string, List<string>>
【发布时间】:2013-09-05 15:17:49
【问题描述】:

我似乎找不到我正在寻找的答案。希望这里有人能帮忙。

我有一个包含某些进程设置信息的类。每个类都有一个 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());

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

"无法转换源类型 System.Collections.Generic.Dictionary<string,System.Generic.List{ProcessStr:string, TaskStr:string}>> 到目标类型 System.Collections.Generic.Dictionary&lt;string,System.Collections.Generic.List&lt;string&gt;&gt;

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

【问题讨论】:

  • 抱歉,无法理解您的字典需要哪些数据

标签: c# linq dictionary lambda


【解决方案1】:

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

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

【讨论】:

  • 无法翻译这个Dictionary&lt;string, List&lt;string&gt; = baseSettings
  • @KingKing:谢谢,已更正。还没有看到语法被破坏了。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-11-27
相关资源
最近更新 更多