tags:

views:

36

answers:

2

I have a Batch with BatchItems entered by multiple users. I'm trying to not only get the subtotal per user for a single batch, but also grand total for that same batch regardless of the user grouping. Its this last part that I can't figure out. How might I get that total in order to return it as a list?

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>()
    }
A: 

Not sure, but try this:

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
    }
STO
Being more familiar with SQL, this looked good to me as well, but the application won't complile b/c of this error - "The name cnt does not exist in the current context."
woodyiii
A: 
        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()


                                            })
                                    )

                  );

Audit Log: Removed previous two code blocks.

Kthurein
"The name g1 does not exist in the current context" - same problem.
woodyiii
Formatting kills my eyes
abatishchev
I've already removed the previous code blocks.
Kthurein