DataTable.Select()显示数据表中记录的总和

时间:2018-05-23 12:07:25

标签: c# .net linq

在DataTable中的C#项目中,我需要总结几列并显示聚合记录,我无法为此创建过滤查询。

记录如下:

|Col1|Col2|Col3|Col4|  
| A  | X  | 10 | 10 |  
| A  | X  | 10 | 20 |  
| A  | Y  | 12 | 12 |  
| A  | Y  | 10 | 10 | 

结果将是:

|Col1|Col2|Col3|Col4|  
| A  | X  | 20 | 30 |  
| A  | Y  | 22 | 22 |  

我必须使用DataTable.Select("filter condition")

1 个答案:

答案 0 :(得分:1)

var result = (from DataRow s in yourDataTable.Select("filter conditions").AsEnumerable()
              group s by new {g1 = s.Field<string>("Col1"), g2 = s.Field<string>("Col2") } into g
              select new
              {
                  Col1 = g.Key.g1,
                  Col2 = g.Key.g2,
                  Col3 = g.sum(r => r.Field<decimal>("Col3")),
                  Col4 = g.sum(r => r.Field<decimal>("Col4")),
               }).ToList();

如果你想把结果作为DataTable类型,你可以将list转换为DataTable,如下所示:

var resultAsDataTable = ConvertListToDataTable(result);

public static DataTable ConvertListToDataTable<T>(IList<T> data)
{
    PropertyDescriptorCollection props =
        TypeDescriptor.GetProperties(typeof(T));
    DataTable table = new DataTable();
    for (int i = 0; i < props.Count; i++)
    {
        PropertyDescriptor prop = props[i];
        table.Columns.Add(prop.Name, prop.PropertyType);
    }
    object[] values = new object[props.Count];
    foreach (T item in data)
    {
        for (int i = 0; i < values.Length; i++)
        {
            values[i] = props[i].GetValue(item);
        }
        table.Rows.Add(values);
    }
    return table;
}