【随记】关于List集合用Linq GroupBy分组过后的遍历小记

时间:2021-11-28 23:28:48

List<LeaderKaoQin> lstLeader = new List<LeaderKaoQin>();//一个List集合
IGrouping<string, LeaderKaoQin> IGroups = null;//由于 group 查询产生的 IGrouping<TKey,?TElement> 对象实质上是列表的列表,所以需遍历2次

List<IGrouping<string, LeaderKaoQin>>    deptLeaders = (from m in lstLeader group m by m.DepName into G orderby G.Key select G).ToList();
            for (int i = 0; i < deptLeaders.Count; i++)
            {
                double deptJB = 0;
                double deptZC = 0;
                IGroups = deptLeaders[i];
                sbDept.Append(string.Format("'{0}',", IGroups.Key));
      //此处需要遍历2次
                foreach (var item in IGroups)
                {
                    deptJB += item.加班;
                    deptZC += item.正常工时;
                }
                sbDeptJB.Append(string.Format("{0},", deptJB.ToString("f2")));//保留2位小数
                sbDeptZC.Append(string.Format("{0},", deptZC.ToString("f2")));
            }

参考资料:
https://msdn.microsoft.com/zh-cn/library/bb384063.aspx