2017-02-23 50 views
0

我有一個Dictionary並希望LINQ -remove所有對(B,A),如果有一對(A,B)。移除所有切換詞典對

Dictionary<int, int> dictionary = new Dictionary<int, int>(); 
dictionary.Add(1, 2); 
dictionary.Add(3, 4); // keep it 
dictionary.Add(4, 3); // remove it 
//dictionary.Add(4, 3); // remove it (ignore this impossible line, @Rahul Singh is right) 
+5

你不能在字典中主要添加項目'4'了!順便說一句,你知道什麼(A,B)是程序如何理解什麼是A?它可以是(4,3)以及正確的?這裏 –

+0

奉勸小心,因爲字典不一定保留插入順序。如果在添加(3,4)之前添加(4,3),您會期望得到不同的輸出嗎? – Softerware

+0

@Softerware:沒有,沒問題,順序並不重要。 – Pollitzer

回答

1

您需要實現自定義相等比較和使用DISTINCT方法。

Dictionary<int, int> dictionary = new Dictionary<int, int>(); 
dictionary.Add(1, 2); 
dictionary.Add(3, 4); 
dictionary.Add(4, 3); 

var result = dictionary.Distinct(new KeyValuePairEqualityComparer()).ToDictionary(x => x.Key, x => x.Value); 
    } 

的相等比較器被定義爲

private class KeyValuePairEqualityComparer : IEqualityComparer<KeyValuePair<int, int>> 
{ 
    public bool Equals(KeyValuePair<int, int> x, KeyValuePair<int, int> y) 
    { 
     return x.Key == y.Value && x.Value == y.Key; 
    } 

    public int GetHashCode(KeyValuePair<int, int> obj) 
    { 
     // Equality check happens on HashCodes first. 
     // Multiplying key/value pairs, ensures that mirrors 
     // are forced to check for equality via the Equals method 
     return obj.Key * obj.Value; 
    } 
} 
+0

不工作,結果在(1,2)。 – Pollitzer

+0

你說得對。我已經更新了答案。我自己的測試(使用您提供的值)現在返回所需的結果。 – mireigi

+0

用'公共類試了一下......'和它的工作! – Pollitzer

0

幼稚的方法是根據需要簡單地過濾它們。

dictionary = dictionary 
.Where(kvp => !(dictionary.ContainsKey(kvp.Value) && dictionary[kvp.Value]==kvp.Key)) 
.ToDictionary(kvp => kvp.Key, kvp => kvp.Value)` 
+0

不工作,結果在(1,2)。 – Pollitzer

0

讓你對是(1,2),去除這對需要從你不要理會值的字典,因爲鑰匙是唯一的。所以,你可以刪除使用下面的代碼:dictionary.Remove(pair.Key);

但對於KeyNotFoundException一個機會,如果指定鍵沒有在集合中找到。所以它總是更好地與刪除操作前要檢查的是:

int value; 
if (dictionary.TryGetValue(pair.Key, out value)) 
{ 
    dictionary.Remove(pair.Key); 
}