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
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:-
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.