linq 将datatable分组求和在转datatable

DataTable dt = new DataTable();
dt.Columns.Add("CustomerID");
dt.Columns.Add("aa");
dt.Columns.Add("vv");
dt.Columns["CustomerID"].DataType = typeof(string);
dt.Columns["aa"].DataType = typeof(Int32);
dt.Columns["vv"].DataType = typeof(Int32);
DataRow row = dt.NewRow();
row["CustomerID"] = "222";
row["aa"] = 1;
row["vv"] = 2;
dt.Rows.Add(row);
DataRow row1 = dt.NewRow();
row1["CustomerID"] = "222";
row1["aa"] = 1;
row1["vv"] = 2;
dt.Rows.Add(row1);
DataRow row11 = dt.NewRow();
row11["CustomerID"] = "3";
row11["aa"] = 1;
row11["vv"] = 2;
dt.Rows.Add(row11);
DataRow row12 = dt.NewRow();
row12["CustomerID"] = "3";
row12["aa"] = 1;
row12["vv"] = 2;

dt.Rows.Add(row12);
var query = from t in dt.AsEnumerable().ToList()
group t by new { t1 = t.Field<string>("CustomerID") } into m
select new
{
name = m.Key.t1,
score = m.Sum(n => n.Field<Int32>("aa")),
ss = m.Sum(n => n.Field<Int32>("vv"))
};


DataTable dt22= ToDataTable(query.Where(p=>1==1));

 

public static DataTable ToDataTable<T>(IEnumerable<T> collection)
{
var props = typeof(T).GetProperties();
var dt = new DataTable();
dt.Columns.AddRange(props.Select(p => new DataColumn(p.Name, p.PropertyType)).ToArray());
if (collection.Count() > 0)
{
for (int i = 0; i < collection.Count(); i++)
{
ArrayList tempList = new ArrayList();
foreach (PropertyInfo pi in props)
{
object obj = pi.GetValue(collection.ElementAt(i), null);
tempList.Add(obj);
}
object[] array = tempList.ToArray();
dt.LoadDataRow(array, true);
}
}
return dt;
}

转载于:https://www.cnblogs.com/zhang-wenbin/p/8807258.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值