Linq to DataTable


1.定义表结构

DataTable DT = new DataTable();


DT.Columns.AddRange(new[]
{
new DataColumn("YDNo",typeof(string)),
new DataColumn("Company",typeof(string)),
new DataColumn("ManageNo",typeof(string)),
new DataColumn("ShareFee",typeof(decimal))
});

DT.Rows.Add("98001", "福永分公司", "IC-001", 0);
DT.Rows.Add("98002", "南山分公司", "IC-002", 0);
DT.Rows.Add("98003", "福田分公司", "IC-002", 0);
DT.Rows.Add("98004", "福永分公司", "IC-001", 0);
DT.Rows.Add("98005", "福永分公司", "IC-003", 0);
View Code

2.Linq Group by

     foreach (DataRow dr in DT.Rows)
            {
                ////求GSCount(根据ManageNo,Company分组,求每个出车编码下不同公司个数)(去除重复数据)
                DataTable dtTemp =
                    DT.AsEnumerable().Cast<DataRow>().GroupBy(p => new { t1 = p.Field<string>("ManageNo"), t2 = p.Field<string>("Company") }).Select(p => p.FirstOrDefault()).CopyToDataTable();

                var GSCount = from r in dtTemp.AsEnumerable() 
                              where r.Field<string>("ManageNo") == dr["ManageNo"].ToStrValue()
                              group r by r.Field<string>("ManageNo") into m
                              select new
                              {
                                  manageNo = m.Key,
                                  mValue = m.Count()
                              };
                var mGSCount = GSCount.First().mValue;

                ////求SamCount(根据ManageNo,Company分组求相同公司区间数)(不去重)
                var SamCount = from r in DT.AsEnumerable()
                               group r by new { t1 = r.Field<string>("ManageNo"), t2 = r.Field<string>("Company") } into m
                               select new
                               {
                                   manageNo = m.Key.t1,
                                   company = m.Key.t2,
                                   mValue = m.Count()
                               };
                var mSamCount = SamCount.First().mValue;

                dr["ShareFee"] = GSCount.First().mValue;
            }
            DT.AcceptChanges();
View Code

 

posted @ 2018-01-09 14:31  Mark1997  阅读(270)  评论(0编辑  收藏  举报