DataTable dt = yourDataTableBefore();
var query = from uu in dt.AsEnumerable()
select new
{
Name= uu.Field<string>("Name"),
Salary = uu.Field<string>("Salary"),
Date = uu.Field<string>("Date"),
Description = uu.Field<string>("Description"),
};
var result = query.GroupBy(cc => cc.Name).Select(dd => new
{
Name = dd.Key,
Salary = string.Join(",",
dd.Select(ee => ee.Salary).ToList()),
Date = dd.Select(ee => ee.Date),
Description = dd.Select(ee => ee.Description),
});
DataTable dt_After = new DataTable();
dt_After.Columns.Add("Name", typeof(string));
dt_After.Columns.Add("Salary", typeof(string));
dt_After.Columns.Add("Date", typeof(string));
dt_After.Columns.Add("Description", typeof(string));
foreach (var item in result.ToList())
{
var newRow = dt_After.NewRow();
Array.ForEach(item.GetType().GetProperties(), p => newRow[p.Name] = p.GetValue(item, null));
dt_After.Rows.Add(newRow);
}
foreach (DataRow row in dt_After.Rows)
{
List<string> List= row["Salary"].ToString().Split(',').ToList();
string Sum_Salary = //Iterate through the list, convert them to int and sum it up;
row["Salary"] = Sum_Salary;
}
Gridview.DataSource = dt_After;
Gridview.DataBind();
您可以在“ var query”中求和,或使用此long方法(以后可以使用数据)。两者都会起作用。我将迭代部分留给您弄清楚(您的功课应该很容易吗,:P)。
希望对您有帮助,最好的问候。
尝试一下。 Ive基本上将具有匹配名称的旧数据表中的行进行了分组,然后对薪水求和,然后使用新分组创建了新数据表。
DataTable new_Table = new DataTable();
new_Table.Columns.Add("Name");
new_Table.Columns.Add("Salary");
new_Table.Columns.Add("Date");
new_Table.Columns.Add("Description");
var groupedByState = old_datatable.AsEnumerable()
.GroupBy(r => r.Field<String>("Name"));
foreach (var group in groupedByState)
{
DataRow maxPremRow = group.OrderByDescending(r => r.Field<String>("Name")).First();
DataRow newRow = new_Table.Rows.Add();
newRow.SetField("id_po", group.Key);
newRow.SetField("Status", maxPremRow.Field<string>("Status"));
newRow.SetField("Cost_ex", group.Sum(r => r.Field<double?>("Cost_ex")));
newRow.SetField("Name", maxPremRow.Field<string>("Name"));
newRow.SetField("Salary", group.Sum(r => r.Field<double?>("Cost_ex")));
newRow.SetField("Description", maxPremRow.Field<string>("Description"));
newRow.SetField("Date", maxPremRow.Field<string>("Date"));
}