LINQ按不同的列计数和分组

时间:2012-06-22 14:07:49

标签: c# linq datatable

id'类似于计算用户编辑或创建的文档数量。因此我有一个包含信息的数据表......像这样:

Input
DocumentName | ModifiedBy | CreatedBy
 a              Frank         Frank
 b              Mike          Frank
 c              John          Mike

那应该是输出:

Name   DocumentsModified(Total)  DocumentsCreated(Total)
Frank      1                        2
Mike       1                        1
John       1                        0

所以它对一个人编辑的所有文件的计数是以下

var query = from queryResult in resultTable.AsEnumerable()
group queryResult by queryResult.Field<string>("ModifiedBy") into rowGroup
select new 
{
    Name = rowGroup.Key, ModifiedDocuments = rowGroup.Count()
};

这很好用。现在我还要计算“创作者”一栏的值。这是可能的,如果是这样,我该怎么做?好的,我可以遍历表,但在LinQ查询中完成此操作会很好。

我尝试使用“group queryResult by new {}”,但我不确定我是否走在正确的轨道上。

2 个答案:

答案 0 :(得分:1)

您不能对CreatedBy使用相同的方法吗?

var query2 = from queryResult in resultTable.AsEnumerable()
group queryResult by queryResult.Field<string>("CreatedBy") into rowGroup
select new 
{
    Name = rowGroup.Key, ModifiedDocuments = rowGroup.Count()
};

然后使用按名称排序的2个查询。

答案 1 :(得分:1)

您最好的选择是分别查询创建和修改,然后将结果与连接组合。

var modifiedCount = from queryResult in resultTable.AsEnumerable()
group queryResult by queryResult.Field<string>("ModifiedBy") into rowGroup
select new 
{
    Name = rowGroup.Key, ModifiedDocuments = rowGroup.Count()
};

var createdCount = from queryResult in resultTable.AsEnumerable()
group queryResult by queryResult.Field<string>("CreatedBy") into rowGroup
select new 
{
    Name = rowGroup.Key, CreatedDocuments = rowGroup.Count()
};

var finalResult = from first in modifiedCount 
                  join second in createdCount
                  on first.Name equal second.Name
                  select new 
                  {
                     first.Name,
                     first.ModifiedDocuments,
                     second.CreatedDocuments 
                  };