获取每个部门的总数

时间:2018-05-18 10:23:18

标签: .net visual-studio linq datatable

此问题是指向Count Duplicates

的链接

我有这样的输出:

Department    Name     Count
Sales         John     2
Sales         Peter    1
Admin         Jack     1
Admin         Sophia   2
Admin         Jill     1
Maintenance   Bob      2
Maintenance   Henry    1

我想使用此信息输出的内容是:

Department    Name     Count
Sales         John     2
Sales         Peter    1
------------------------
Total                  3
------------------------
Admin         Jack     1
Admin         Sophia   2
Admin         Jill     1
------------------------
Total                  4
------------------------
Maintenance   Bob      2
Maintenance   Henry    1
------------------------
Total                  3
------------------------

我使用以下代码输出第一个列表:

var query = data.AsEnumerable()
                .GroupBy(r => new { Dept = r.Field<string>("Department"),
                    Name = r.Field<string>("FirstName"),
                    Surname = r.Field<string>("LastName")})
                .Select(grp => new
                {
                    Dept = grp.Key.Dept,
                    Name = grp.Key.Name,
                    Surname = grp.Key.Surname,
                    Count = grp.Count()
                });

            foreach(var item in query)
            {
                newData.Rows.Add(item.Dept, item.Name, item.Surname, item.Count);
            }

如何为每个部门添加总计数?

1 个答案:

答案 0 :(得分:2)

data.AsEnumerable()
  .GroupBy(r => r.Field<string>("Department"))
  .ToDictionary(g => g.Key, g => g.Count());

这将为您提供Dictionary<string, int>,其中键是部门名称,值是计数。