2011-11-27 59 views
1

你怎么称呼这种方法,(是在.NET中可用?)名ASSOC-DIFF的

var list1 = new List<int>() { 1, 2, 2, 3, 4 }; 
var list2 = new List<int>() { 1, 2, 3}; 
var results = list1.diff(list2); 

results: 
{ 2, 4 } 

回答

1

这正是回报你想要什么,你可以在一个扩展方法重构它:

var results = list1.GroupBy(p => p).Select(p => new { item = p.Key, count = p.Count() }) 
       .Concat(list2.GroupBy(p => p).Select(p => new { item = p.Key, count = -p.Count() })) 
       .GroupBy(p => p.item).Select(p => new { item = p.Key, count = p.Sum(q => q.count) }) 
       .Where(p => p.count > 0) 
       .SelectMany(p => Enumerable.Repeat(p.item, p.count)); 
+0

非常好!我学到了一些新的东西:) – kobi7

2

建于最接近的事是Except LINQ运营商。

产生两个序列的设定差异。

虽然你的榜样,将导致:

{ 4 } 

我不相信有一个直接模拟你想要什么。

+0

我可以实现它与字典 但我不确定它会如此高效。 – kobi7

+0

@比土壤好 - 可能。 – Oded

0

像这样:(见俄德对一个LINQ到MSDN后)

int[] numbersA = { 0, 2, 4, 5, 6, 8, 9 }; 
int[] numbersB = { 1, 3, 5, 7, 8 }; 

IEnumerable<int> aOnlyNumbers = numbersA.Except(numbersB); 
2

你真的需要多集的实现。尽管在BCL中没有开箱即用,但有一些想法herelinked question

或者你可以真正实现一个自己,这不是那么复杂:

class Multiset<K> // maybe implement IEnumerable? 
{ 
    Dictionary<K, int> arities = new Dictionary<K, int>(); 
    ... 
    Multiset<K> Except(Multiset<K> other) 
    { 
     foreach (var k in arities.keys) 
     { 
      int arity = arities[k]; 
      if (other.Contains(k)) 
       arity -= other.Arity(k); 
      if (arity > 0) 
       result.Add(k, arity); 
     } 
     return result; 
    } 
}