1

我在内存中有 2 组冷却,我想根据 2 返回一组。我的对象具有以下结构:

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;

有人可以告诉我应该如何构建我的自定义相等比较器来获得这个结果吗?

提前谢谢了

4

1 回答 1

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)
                                 });
于 2013-08-22T14:29:37.037 回答