【问题标题】:Convert Datatable GroupBy Multiple Columns with Sum using Linq使用 Linq 将 Datatable GroupBy 多列与 Sum 转换
【发布时间】:2014-12-09 12:03:49
【问题描述】:

我想在 Group BY 之后对所有 TotalImages 列求和,但它显示错误。 任何可以帮助我的人出了什么问题。 请记住,只想使用此语法库并希望 DataTable 不是 List。如果有人帮助我,将不胜感激。

样本数据:-

CountryId | CItyId | TotalImages
1              1        2
1              2        2
1              2        3
1              3        4 
2              1        2
2              2        2
2              2        3
2              3        4 




DataTable dt = dt.AsEnumerable()
 .GroupBy(r => new { Col1 = r["CountryId"], Col2 = r["CityId"]})
 .Select(g => g.Sum(r => r["TotalImages"]).First())
 .CopyToDataTable();

【问题讨论】:

  • 分享您的DataTable 的结构以及示例数据(如果可能)。
  • @RahulSingh 你可以假设 CountryId |城市标识 |总图像 1 1 2 1 2 2 1 2 3 1 3 4 2 1 2 2 2 2 2 2 3 2 3 4

标签: c# linq datatable


【解决方案1】:

你可以用这个:-

DataTable countriesTable = dt.AsEnumerable().GroupBy(x => new { CountryId = x.Field<int>("CountryId"), CityId = x.Field<int>("CityId") })
                             .Select(x => new Countries
                                          {
                                              CountryId = x.Key.CountryId,
                                              CityId = x.Key.CityId,
                                              TotalSum = x.Sum(z => z.Field<int>("TotalImages"))
                                          }).PropertiesToDataTable<Countries>();

我得到,以下输出:-

由于我们不能将CopyToDataTable 方法用于匿名类型,因此我使用了从here 获取的扩展方法并进行了相应的修改。

public static DataTable PropertiesToDataTable<T>(this IEnumerable<T> source)
    {
        DataTable dt = new DataTable();
        var props = TypeDescriptor.GetProperties(typeof(T));
        foreach (PropertyDescriptor prop in props)
        {
            DataColumn dc = dt.Columns.Add(prop.Name, prop.PropertyType);
            dc.Caption = prop.DisplayName;
            dc.ReadOnly = prop.IsReadOnly;
        }
        foreach (T item in source)
        {
            DataRow dr = dt.NewRow();
            foreach (PropertyDescriptor prop in props)
            {
                dr[prop.Name] = prop.GetValue(item);
            }
            dt.Rows.Add(dr);
        }
        return dt;
    }

还有,这里是Countries 类型:-

public class Countries 
{
    public int CountryId { get; set; }
    public int CityId { get; set; }
    public int TotalSum { get; set; }
}

如果您愿意,可以使用任何其他方法将其转换为 DataTable。

【讨论】:

  • 行添加显示错误时遇到给定函数的问题。此行已属于此表。在这条线上 dt.Rows.Add(dr);当我更改为 dr.Import 函数时,没有数据返回。如果我正在更改 dt.Rows.Add(dr.ItemArray);然后它创建了非常奇怪的表,例如空行重复。
  • @Wajihurrehman - 您是否使用相同的数据表,我的意思是您在问题中发布的值?我使用了相同的数据,它按预期工作,我也分享了输出屏幕截图。
  • 不,实际上它只是一个样本。但根据您的代码,它应该适用于所有类型。
  • @Wajihurrehman - 嗯,我也想知道。我重新检查了代码,它对我来说工作正常。
  • @Wajihurrehman - 嘿伙计,在解决一些其他问题时,我遇到了同样的问题 this row already belongs to this table,您提到的问题已更正,请检查。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2023-03-30
  • 1970-01-01
  • 1970-01-01
  • 2012-04-20
  • 1970-01-01
  • 1970-01-01
  • 2017-11-16
相关资源
最近更新 更多