2016-04-26 61 views
1

我有一個由模型定義的對象列表,我想按特定字段進行分組。分組時,有些字段需要彙總在一起。我想按ItemName進行分組,金額將全部彙總在一起。按組和按型號選擇

我的模式是:

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

我現在的嘗試是:

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) 
          } 
         ); 

我得到一個錯誤,每個鍵語句之後,他說,分組模式不包含ITEMNAME一個確定指標。

任何幫助,將不勝感激。謝謝。

+0

確保您已經在您的使用列表中包含'使用System.Linq' –

+0

已經有了,就在頂端 – JoeFromAccounting

回答

3

你的代碼看起來應該是這樣

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(); 
  • 代替i.Key.ItemColor你有項的列表,你必須選擇一個值(例如First()) - Key是每組
  • ItemName