Linq表达式将DataTable转换为<键,值列表>字典

5

I am trying to convert a DataTable of the form

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',因为它不是委托类型”

我该如何解决这个问题呢?

3个回答

4
这就完成了:
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());

1
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));
    }

}

1
这不完全是我想要的,但ToLookup确实非常有用 - 谢谢。 - Ryan

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接