Convert Datatable GroupBy Multiple Columns with Sum using Linq

前端 未结 1 354
时光取名叫无心
时光取名叫无心 2021-01-28 21:24

I want to sum of all TotalImages Column after Group BY but its\' showing me error. any one who can help me what\'s going wrong. Remember just want to use from this syntax base a

1条回答
  •  抹茶落季
    2021-01-28 22:15

    You can use this:-

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

    I am getting, following output:-

    enter image description here

    Since, We cannot use CopyToDataTable method for anonymous types, I have used an extension method took from here and modified it accordingly.

    public static DataTable PropertiesToDataTable(this IEnumerable 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;
        }
    

    And, here is the Countries type:-

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

    You can use any other approach to convert it to a DataTable if you wish.

    0 讨论(0)
提交回复
热议问题