2015-10-05 202 views
-1

我有以下代碼:在字典刪除重複<INT,列表<PointF>>

Dictionary<int, List<PointF>> dictEntities = new Dictionary<int, List<PointF>>(); 
dictEntities.Add(1, new List<PointF>() { new PointF(1.0F, 2.0F), new PointF(3.0F, 4.0F) }); 
dictEntities.Add(2, new List<PointF>() { new PointF(3.0F, 4.0F), new PointF(1.0F, 2.0F) }); 
dictEntities.Add(3, new List<PointF>() { new PointF(7.0F, 8.0F), new PointF(9.0F, 6.0F) }); 

我想刪除字典條目,其列出了重複。 刪除重複項後的預期結果:詞典現在包含2個條目(「1」和「3」或「2」和「3」),因爲條目1和2具有相同的PointF列表。 1或2從字典中刪除。我想我必須首先對列表進行排序,然後以某種方式對其進行區分?但是,如何實際刪除重複的條目?

我至今嘗試過是這樣的:

foreach (var item in dictEntities.ToList()) 
{ 
    while (dictEntities.Values.Contains(item.Value)) 
    { 
     dictEntities.Remove(item.Key); 
    } 
} 

但這總是清空整部字典。我必須以某種方式解決它。

謝謝

+0

你嘗試過什麼到目前爲止,和你看到的結果嗎?一旦你嘗試了一些人們很樂意提供幫助,但通常他們希望首先看到一些努力。 –

+0

Linq在這裏不太合適,它只會看起來像代碼高爾夫。只需使用嵌套的foreach或實際的設計模式來爲您的行爲建模,而不是使用一組列表的字典。 –

+0

你的列表中總是有2個'PointF'值嗎?如果是這樣,看起來你會更好地與自定義類包含這個,而不是列表。 – DavidG

回答

2

你可以用自定義IEqualityComparer和使用GroupBy做到這一點。例如:

public class MyComparer : IEqualityComparer<List<PointF>> 
{ 
    public bool Equals(List<PointF> l1, List<PointF> l2) 
    { 
     //If lists contain different amount of items, they are different 
     if(l1.Count() != l2.Count()) return false; 

     //Order the lists by X then Y, that way we can compare them in order 
     var orderedL1 = l1.OrderBy(p => p.X).ThenBy(p => p.Y).ToList(); 
     var orderedL2 = l2.OrderBy(p => p.X).ThenBy(p => p.Y).ToList(); 

     for(var i = 0; i < l1.Count(); i++) 
     { 
      if(orderedL1[i].X != orderedL2[i].X) return false; 
      if(orderedL1[i].Y != orderedL2[i].Y) return false; 
     } 

     //They must be the same if we reached here 
     return true; 
    } 

    public int GetHashCode(List<PointF> dp) 
    { 
     return 0; 
    } 
} 

而且使用這樣的:

var distinctList = dictEntities 
    .GroupBy(de => de.Value, new MyComparer()) 
    .Select(de => de.Key); 

如果你想保持它作爲一本字典,而不是Select,使用ToDictionary並把你方法的順位選擇的關鍵。下面是一個例子使用First(這意味着你會從你的例子項目1和3):

var distinctList = dictEntities 
    .GroupBy(de => de.Value, new MyComparer()) 
    .ToDictionary(g => g.First().Key, g => g.Key); 
+0

非常感謝!你能告訴我如何檢索一個字典與你的用法示例?我需要原始字典中的密鑰。 –

+0

@KarlRanseier檢查編輯。 – DavidG

相關問題