2011-11-27 20 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; 
    } 
}