JoeFromAccounting
JoeFromAccounting

Reputation: 145

Group by and Select with Models

I have a list of an object defined by a model, and I want to group by a specific field. When grouped, some fields will need to be summed together. I want to group by ItemName, and the Amount will be all summed together.

My model is:

public class Item{
    public string ItemName { get; set; }
    public string ItemColor { get; set; }
    public string SomethingElse { get; set; }
    public decimal Amount { get; set; }
}

My current attempt is:

List<Item> fullListOfItems = GetItemsFromDatabase();

List<Item> groupedList = fullListOfItems
                         .GroupBy( l => l.ItemName )
                         .Select(i =>
                             new Item() 
                             {
                                 ItemName = i.Key.ItemName,
                                 ItemColor = i.Key.ItemColor,
                                 SomethingElse = i.Key.SomethingElse,
                                 Amount = i.Sum(k=>k.Amount)
                             }
                         );

I'm getting an error after each key statement, saying that the grouping model does not contain a defintion for ItemName.

Any help would be appreciated. Thanks.

Upvotes: 1

Views: 2615

Answers (1)

fubo
fubo

Reputation: 45947

your code should look like this

List<Item> groupedList = fullListOfItems
                            .GroupBy(l => l.ItemName)
                            .Select(i =>
                                new Item()
                                {
                                    ItemName = i.Key,
                                    ItemColor = i.First().ItemColor,
                                    SomethingElse = i.First().SomethingElse,
                                    Amount = i.Sum(k => k.Amount)
                                }
                            ).ToList();
  • instead of i.Key.ItemColor you have a List of Items and you have to pick one value (e.g. First()) - Key is the value of ItemName of each group

Upvotes: 3

Related Questions