2013-08-22 28 views
1

工會我有2組內存coolection的,我想基於2.我的對象返回一組有以下suructure:相交或使用自定義的IEqualityComparer使用LINQ

class Item 
{ 
    public string key {get,set;} 
    public int total1 {get;set;} 
    public int total2 {get ;set;} 
} 

我想「聯合」起來,這樣,當項目表格上的按鍵設置1等於從設定的2項的關鍵,我的工會應返回的項目如下:

item_union.Key= item1.key==item2.key; 
item_union.total1= item1.total1 + item2.total1; 
item_union.total2= item1.total2 + item2.total2; 

能有人告訴我我應該如何建立我自定義的平等比較器來獲得這個結果?

提前很多感謝

+0

每個集合中是否只有一個具有特定鍵的項目?對於在其他收藏中沒有相應密鑰的物品,您希望發生什麼? –

+0

一般而言,這將是一個雙方同樣的關鍵項目。當它在一邊缺少時,我只使用那個在場的人。非常感謝 –

+0

好的,在這種情況下,我認爲我的答案應該沒問題。不需要交叉點或聯合。 –

回答

2

這聽起來像你可能想聯接,或者你威力只是想連接的集合,按鍵,然後總結屬性:

// Property names changed to conform with normal naming conventions 
var results = collection1.Concat(collection2) 
         .GroupBy(x => x.key) 
         .Select(g => new Item { 
            Key = g.Key, 
            Total1 = g.Sum(x => x.Total1), 
            Total2 = g.Sum(x => x.Total2) 
           }); 
+0

優秀,這意味着我不需要一個custum IEqualityComaprer!那看起來很優雅。我會嘗試。 –

相關問題