我在c#中有一個列表,該列表包含結構,我想刪除重複結構,但只是具有某些字段相等的結構。 我該怎麼辦? THX按字段刪除結構列表
0
A
回答
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
有兩種可能的解決方案:
- 用手移除重複:通過列表意味着迭代嵌套循環。
- 指定結構散列碼和相等性檢查,並使用
Hashset<YourStruct>
刪除重複項。這可以通過自定義IEqualityComparer
(link)實現來完成,或者如果通過使用適當的GetHashCode
和Equals
方法重寫實現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());
相關問題
- 1. 刪除空結構字段Matlab的
- 2. 獲取結構中的字段列表
- 3. 分段錯誤刪除與結構是按鍵
- 4. 陣列結構和新/刪除
- 5. 結構與列表<..>在2 dim。動態數組段錯誤刪除
- 6. 刪除WooCommerce結帳字段值
- 7. 如何從結構列表中刪除1結構如果匹配變量?
- 8. 按不同字段排序結構隊列
- 9. MySQL字段結構
- 10. 如何從STL列表中刪除結構記錄
- 11. Golang地圖或結構添加或從列表中刪除
- 12. Datagrid +地圖列結構字段
- 13. C++:刪除一個結構?
- 14. 刪除列字段中的「TRIM」?
- 15. MATLAB:從結構中的字段中刪除非唯一的數字
- 16. 帶結構字段指針的結構
- 17. 按層次結構排序列表
- 18. 刪除看不見的表單字段
- 19. 在表單上添加/刪除字段
- 20. Bootstrap:刪除表單字段邊框
- 21. jQuery的刪除表單輸入字段
- 22. 幫助從HTML表中刪除字段
- 23. 清除列表中的結構元素
- 24. 記事本++按列表刪除單詞
- 25. 列表控件在刪除鍵上刪除行按
- 26. 刪除按鈕不刪除列表框中的項目
- 27. 按字符刪除字符
- 28. 刪除列表
- 29. 解決在GraphQL列表字段沒有結構
- 30. extjs從字段集中刪除字段
氣味像功課 –
@Rubens法里亞斯,不是一切是你知道的功課。業務中甚至有愚蠢/瑣碎/容易的事情,有時甚至是頂級程序員都可能會錯過它們。 – Dani
你能說清楚一個例子,不知道我是否得到要求 – SWeko