【问题标题】:group by multiple columns (Dynamically) of datatable by linq Query通过 linq Query 按数据表的多列(动态)分组
【发布时间】:2013-07-04 13:13:18
【问题描述】:

我想通过 linq 查询对数据表中的多列进行分组。

我试过这样,

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]))),
};

它工作正常。我的问题是我在 strToolTip 数组中有 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])))
   }   
};

并且还想动态添加数据类型,请提供解决此问题的答案。 linq 查询对我来说是新的。

【问题讨论】:

    标签: c# linq


    【解决方案1】:

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

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

    【讨论】:

      【解决方案2】:

      感谢 ChaseMedallion,我得到了动态分组工作。 Equals 方法还不够,我还得把GetHashCode 加到MyComparer 上:

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2018-06-14
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-09-02
        • 2014-12-09
        相关资源
        最近更新 更多