Lambda expression Group by in C#

KLIM8D picture KLIM8D · Jan 24, 2012 · Viewed 34.2k times · Source

I would like to group my LINQ query by ItemNumber and return the whole table with the total for Quantity.

Example:
ItemNumber - ItemName - Quantity
100          Item1       1
150          Item2       2
100          Item1       2
200          Item3       1
150          Item2       2

Should be:
ItemNumber - ItemName - Quantity
100          Item1       3
150          Item2       4
200          Item3       1

This is the query I am trying to group:

public IQueryable<WebsiteOrderStatus> GetOrderStatusByAccountNumberWithoutDeleted
        (string accountNumber)
{
    return db.WebsiteOrderStatus
             .Where(x => x.AccountNumber == accountNumber && x.LastUpdatedStatus != 1);
}

And my best result so far(this can't compile though):

public IQueryable<IGrouping<Int32?, WebsiteOrderStatus>> lol(string accountNumber)
{
     db.WebsiteOrderStatus
       .Where(x => x.AccountNumber == accountNumber && x.LastUpdatedStatus != 1)
       .GroupBy(g => g.ItemNumber)
       .Select(g => new
                    {
                         g.Key.ItemNumber,
                         Column1 = (Int32?)g.Sum(p => p.Quantity)
                    });
 }

EDIT:

Thanks for the replies everyone, I must face it. Theese anonymous types are pretty hard to work with in my opinion, so I found another solution.

I made another method, which sums the quantity of the users items and grouped the first one.

public IQueryable<WebsiteOrderStatus> GetOrderStatusByAccountNumberWithoutDeleted(string accountNumber)
{
    return db.WebsiteOrderStatus.Where(x => x.AccountNumber == accountNumber && x.LastUpdatedStatus != 1).GroupBy(x => x.ItemNumber).Select(grp => grp.First());
}

public int GetQuantityOfUsersItem(string accountNumber, string itemNumber)
{
    return db.WebsiteOrderStatus.Where(x => x.ItemNumber == itemNumber && x.AccountNumber == accountNumber).Sum(x => x.Quantity);
}

At the page where I have my gridview I did:

var query = websiteOrderStatusRep.GetOrderStatusByAccountNumberWithoutDeleted(AppSession.CurrentLoginTicket.AccountNumber).Select(x => new { x.ItemName, x.ItemNumber, x.FormatName, x.Price, x.Status, x.Levering, Quantity = websiteOrderStatusRep.GetQuantityOfUsersItem(x.AccountNumber, x.ItemNumber)});

Answer

vc 74 picture vc 74 · Jan 24, 2012
public IQueryable<IGrouping<Int32?, WebsiteOrderStatus>> lol(string accountNumber)
{
     db.WebsiteOrderStatus
       .Where(x => x.AccountNumber == accountNumber && x.LastUpdatedStatus != 1)
       .GroupBy(g => g.ItemNumber)
       .Select(g => new
                    {
                         ItemNumber = g.Key,
                         ItemName = g.First().ItemName,
                         Count = g.Sum(item => item.Quantity)
                    });
 }