LINQ Group By Subtotal&总

时间:2010-06-18 20:49:01

标签: linq group-by

我有一个Batch,其中BatchItems由多个用户输入。我不仅尝试获得单个批次的每个用户的小计,而且还尝试获得同一批次的总计小计,无论用户分组如何。这是我无法弄清楚的最后一部分。我如何才能获得该总数以便将其作为列表返回?

from b in context.BatchItem
    where b.BatchId == batchId
    group b by b.CreatedByUser into g
    select new
    {
        BatchName = g.FirstOrDefault<BatchItem>().Batch.Name,
        User = g.Key,
        UserBatchCount = g.Count<BatchItem>(),
        // something like this is what I can't figure out
        TotalBatchCount = b.Count<BatchItem>()
    }

2 个答案:

答案 0 :(得分:0)

不确定,但试试这个:

from b in context.BatchItem
let cnt = context.BatchItem.Count()
b.BatchId == batchId
group b by b.CreatedByUser into g
select new
    {
        BatchName = g.FirstOrDefault<BatchItem>().Batch.Name,
        User = g.Key,
        UserBatchCount = g.Count<BatchItem>(),
        // something like this is what I can't figure out
        TotalBatchCount = cnt
    }

答案 1 :(得分:0)

        var batch1 = new { Name = "Batch A", BatchId = 1, CreatedByUser = "David" };
        var batch2 = new { Name = "Batch A", BatchId = 1, CreatedByUser = "Mike" };
        var batch3 = new { Name = "Batch B", BatchId = 2, CreatedByUser = "Cathy" };
        var batch4 = new { Name = "Batch B", BatchId = 2, CreatedByUser = "Cathy" };
        var batch5 = new { Name = "Batch B", BatchId = 2, CreatedByUser = "David" };
        var batch6 = new { Name = "Batch C", BatchId = 3, CreatedByUser = "Henry" };
        var batchItem = new[] { batch1, batch2, batch3, batch4, batch5, batch6 }.ToList();


        var result =
        batchItem.Where(b => b.BatchId == batchId)
                 .GroupBy(b => b.BatchId, b => b)
                 .SelectMany(g =>
                        g.GroupBy(c => c.CreatedByUser, c => c)
                         .SelectMany(sg =>
                                            sg.Select(c => new
                                            {
                                                BatchName = g.First().Name,
                                                UserName = c.CreatedByUser,
                                                UserBatchCount = sg.Count(),
                                                TotalBatchCount = g.Count()


                                            })
                                    )

                  );

审核日志:删除了前两个代码块。

相关问题