2011-09-06 48 views
0

我在c#中有一個列表,該列表包含結構,我想刪除重複結構,但只是具有某些字段相等的結構。 我該怎麼辦? THX按字段刪除結構列表

+1

氣味像功課 –

+0

@Rubens法里亞斯,不是一切是你知道的功課。業務中甚至有愚蠢/瑣碎/容易的事情,有時甚至是頂級程序員都可能會錯過它們。 – Dani

+1

你能說清楚一個例子,不知道我是否得到要求 – SWeko

回答

0
List<Sample> samples = new List<Sample>(new[] 
{ 
    new Sample {Id = 1}, 
    new Sample {Id = 1}, 
    new Sample {Id = 2}, 
    new Sample {Id = 3}, 
    new Sample {Id = 1} 
}); 

var duplicates = samples 
    .Select ((s, i) => new { s.Id, Index = i }) // Get item key and index 
    .GroupBy (s => s.Id)       // Group by Key 
    .Where  (g => g.Count() > 1)     // Get duplicated ones 
    .SelectMany(g => g.Skip (1)      // We'll keep first one 
         .Select(i => i.Index))  // Get other items ids 
    .Reverse(); 
foreach (var index in duplicates) 
{ 
    samples.RemoveAt(index); 
} 
0

有兩種可能的解決方案:

  1. 用手移除重複:通過列表意味着迭代嵌套循環。
  2. 指定結構散列碼和相等性檢查,並使用Hashset<YourStruct>刪除重複項。這可以通過自定義IEqualityComparerlink)實現來完成,或者如果通過使用適當的GetHashCodeEquals方法重寫實現IEquatable接口來「擁有」結構。

如果你的設置很小,而且這個操作必須在你的代碼中執行一次,那麼我會尋求解決方案之一。但是如果這種比較邏輯一遍又一遍地使用,我會去解決方案二。

執行情況的解決方案二:

struct YourStruct 
    { 
     public int Id; 
    } 

    class Comparer : IEqualityComparer<YourStruct> 
    { 

     public bool Equals(YourStruct a, YourStruct b) 
     { 
     return a.Id == b.Id; 
     } 


     public int GetHashCode(YourStruct s) 
     { 
     return s.Id; 
     } 

    } 

    List<YourStruct> list = new List<YourStruct>(); 

    HashSet<YourStruct> hs = new HashSet<YourStruct>(list, new Comparer()); 
+0

thx !,如果想比較一個類而不是結構體的對象? – jobormo

+0

差不多。只要你實現你自己的'GetHashCode'和'Equals'。 – Stefan