Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/linq/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/csharp-4.0/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
使用Linq与自定义IEqualityComparer相交或并集_Linq_C# 4.0 - Fatal编程技术网

使用Linq与自定义IEqualityComparer相交或并集

使用Linq与自定义IEqualityComparer相交或并集,linq,c#-4.0,Linq,C# 4.0,我有2套coolection在内存中,我想返回一套基于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.t

我有2套coolection在内存中,我想返回一套基于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;
有人能告诉我如何构建自定义平等比较器以获得此结果吗

非常感谢您提前

听起来您可能想要加入,或者您可能只想连接集合,按键分组,然后对属性求和:

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

每个集合中是否只有一个具有特定密钥的项?对于在另一个集合中没有相应键的项目,您希望如何处理?通常情况下,两侧都具有相同键的项目。当它在一边丢失时,我只使用现在的那一个。非常感谢,如果是那样的话,我想我的答案应该是好的。不需要交叉路口或工会。太好了,这意味着我不需要客户资格认证!那看起来很优雅。我试试看。