C# 通过linq查询按datatable的多列(动态)分组

C# 通过linq查询按datatable的多列(动态)分组,c#,linq,C#,Linq,我想通过linq查询在datatable中按多个列分组 我试着这样做 var _result = from row in tbl.AsEnumerable() group row by new { id=row.Field<object>(_strMapColumn), value=row.Field<object>(_strValueColumn), } into g select new { _strMapColumn = g.Key.id,

我想通过linq查询在datatable中按多个列分组

我试着这样做

var _result = from row in tbl.AsEnumerable()

group row by new
{
    id=row.Field<object>(_strMapColumn),
    value=row.Field<object>(_strValueColumn),
} into g
select new
{
    _strMapColumn = g.Key.id,
    ToolTip = g.Sum(r => grp.Sum(r => r.Field<Double>(__strToolTip[1]))),
};
var\u result=来自tbl.AsEnumerable()中的行
按“新建”分组行
{
id=行字段(\u strMapColumn),
值=行.字段(\u strValueColumn),
}进入g
选择新的
{
_strMapColumn=g.Key.id,
工具提示=g.Sum(r=>grp.Sum(r=>r.Field(\uu strtoltip[1])),
};
它很好用。我的问题是,我在strtoltip数组中有10个列名,我想像for循环一样动态访问10个列名,有可能吗

我想要这样

select new
{_strMapColumn = g.Key.id,

   for(int index = 1; index <= 10; index++)
   {    
       ToolTip+index = g.Sum(r => getDoubleValue(r.Field<Double>(__strToolTip[1])))
   }   
};
选择新建
{u strMapColumn=g.Key.id,
for(int index=1;index getDoubleValue(r.Field(\uu strtoltip[1]))
}   
};
并且还想动态添加一个数据类型,请提供解决这个问题的答案。
linq查询对我来说是新的。

您可以通过字典分组并传递自定义比较器:

public class MyComparer : IEqualityComparer<Dictionary<string, object>> {
    public bool Equals(Dictionary<string, object> a, Dictionary<string, object> b) {
        if (a == b) { return true; }
        if (a == null || b == null || a.Count != b.Count) { return false; }
        return !a.Except(b).Any();
    }
}

IEnumerable<string> columnsToGroupBy = ...
var rows = tbl.AsEnumerable();
var grouped = rows.GroupBy(r => columnsToGroupBy.ToDictionary(c => c, c => r[c]), new MyComparer());
var result = grouped.Select(g => {
    // whatever logic you want with each grouping
    var id = g.Key["id"];
    var sum = g.Sum(r => r.Field<int>("someCol"));
});
公共类MyComparer:IEqualityComparer{
公共布尔等于(字典a、字典b){
如果(a==b){返回true;}
如果(a==null | | b==null | | a.Count!=b.Count){return false;}
return!a.除了(b).Any();
}
}
IEnumerable columnsToGroupBy=。。。
var rows=tbl.AsEnumerable();
var grouped=rows.GroupBy(r=>columnsToGroupBy.ToDictionary(c=>c,c=>r[c]),new MyComparer();
变量结果=分组。选择(g=>{
//每个分组都有您想要的逻辑
var id=g.Key[“id”];
var sum=g.sum(r=>r.Field(“someCol”);
});

多亏了ChaseMedallion,我的动态分组工作正常。 Equals方法还不够,我还必须将
GetHashCode
添加到
MyComparer
中:

public int GetHashCode(Dictionary<string, object> a)
{
    return a.ToString().ToLower().GetHashCode();
}
public int GetHashCode(字典a)
{
返回a.ToString().ToLower().GetHashCode();
}