【问题标题】:Linq Expression to Turn DataTable to Dictionary of <Key, List<Values>>Linq 表达式将 DataTable 转换为 <Key, List<Values>> 的字典
【发布时间】:2014-02-07 02:02:47
【问题描述】:

我正在尝试转换表单的 DataTable

Key  Value
1    A
1    B
1    C
2    X
2    Y

到字典

1 [A,B,C]
2 [X,Y]

我使用的 lambda 表达式是

GetTable("..sql..").AsEnumerable().
    .Select(r => new {Key = r.Field<int>("Key"), Val = r.Field<string>("Value")})
    .GroupBy(g => g.Key)
    .ToDictionary(a => a.Key, a => String.Join(",", a.Value))

但它失败并显示“无法将 lambda 表达式转换为类型 'System.Collections.Generic.IEqualityComparer',因为它不是委托类型”

我怎样才能做到这一点?

【问题讨论】:

    标签: c# linq


    【解决方案1】:

    这样做:

    GetTable("..sql..").AsEnumerable().
        .Select(r => new {Key = r.Field<int>("Key"), Val = r.Field<string>("Value")})
        .GroupBy(g => g.Key)
        .ToDictionary(a => a.Key, a => String.Join(",", a.Select(x => x.Value).ToList()))
    

    【讨论】:

      【解决方案2】:

      这是另一种方法......

      GetTable("..sql..").AsEnumerable()
          .GroupBy(x => x.Field<int>("Key"))
          .ToDictionary(grp => grp.Key, x => x.Select(y => y.Field<string>("Value")).ToList());
      

      【讨论】:

        【解决方案3】:
        var foo = GetTable("").AsEnumerable()
                         .ToLookup(x => x.Key, x => x.Value);
        foreach(var x in foo)
        {
            foreach(var value in x)
            {
                Console.WriteLine(string.Format("{0} {1}", x.Key, value));
            }
        
        }
        

        【讨论】:

        • 这不是我所追求的,但 ToLookup 真的很有用 - 谢谢。
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2019-09-15
        • 1970-01-01
        • 1970-01-01
        • 2020-12-15
        • 1970-01-01
        • 2013-11-11
        • 2022-01-01
        相关资源
        最近更新 更多