2010-03-22 81 views
2

我需要一些幫助將條件添加到linq查詢中。LINQ根據返回的結果進行分組並根據返回的結果創建公式

拿這個小例子

static void Main(string[] args) 
    { 
     List<ItemEntry> items = new List<ItemEntry>(); 
     items.Add(new ItemEntry(1,1,5,1)); 
     items.Add(new ItemEntry(2, 1, 5, 1)); 
     items.Add(new ItemEntry(3, 1, 5, 1)); 
     items.Add(new ItemEntry(4, 1, 10, 3)); 
     items.Add(new ItemEntry(5, 2, 5, 1)); 
     items.Add(new ItemEntry(6, 2, 5, 1)); 
     items.Add(new ItemEntry(7, 2, 5, 1)); 
     items.Add(new ItemEntry(8, 2, 5, 1)); 
     items.Add(new ItemEntry(9, 2, 5, 2)); 
     items.Add(new ItemEntry(10, 2, 5, 2)); 

     var results = from data in items 
         group data by data.ItemTypeID 
          into grouped 
          select new { ItemID = grouped.Key, ItemPrice = grouped.Sum(data => data.ItemPrice) }; 

     foreach (var item in results) 
     { 
      Console.WriteLine(item.ItemID + " " + item.ItemPrice); 
     } 

     Console.ReadLine(); 

    } 
} 
public class ItemEntry 
{ 
    public int ItemID { get; set; } 
    public int ItemTypeID { get; set; } 
    public double ItemPrice { get; set; } 
    public int ProcessedType { get; set; } 

    public ItemEntry(int itemID, int itemTypeID,double itemPrice, int processedType) 
    { 
     ItemID = itemID; 
     ItemTypeID = itemTypeID; 
     ItemPrice = itemPrice; 
     ProcessedType = processedType; 
    } 
} 

我分組然後ItemTypeID基於這是很好的組作成的總和。我現在需要添加額外的2個條件。 我想保持分組相同,但我只想在ProcessedType == 1的情況下做同樣的事情,如果它的類型爲2或3,那麼我想總計它們,然後減去它分組總數。

例如我將使用ItemTypeID 1 如果我總計所有ProcessedType 1我得到15,如果我總ProcessedType3我有10所以我想返回5.

我不知道如何將條件添加到我的代碼。

任何幫助將是偉大的!

TIA

回答

0

添加一個新的屬性給你的班級,爲你做的工作。

public class ItemEntry 
{ 
    // keep the existing properties 
    ... 

    public int TotalModifier 
    { 
     get 
     { 
      if (this.ProcessedType == 1) 
       return this.ItemPrice; 
      else 
       return -(this.ItemPrice); 
     } 
    } 

現在總結新物業

var results = from data in items 
        group data by data.ItemTypeID 
         into grouped 
         select new { ItemID = grouped.Key, ItemPrice = grouped.Sum(data => data.TotalModifier) }; 

你想給這個屬性比我有更好的名字,但邏輯是有你。

+0

H柯克感謝您的回覆。這是一個夢想:) – 2010-03-22 17:19:07

+0

對不起還有一個問題。而不是使用通用列表來獲取如果我想使用LINQ-SQL的值。假設所有的字段都有相同的名稱,但是我沒有在數據庫中的TotalModifier字段。 對不起,我對linq很新穎 – 2010-03-22 19:50:51