按字段删除结构列表
我在 C# 中有一个列表,该列表包含结构,我想删除重复的结构,但只删除某些字段相等的结构。 我该怎么办? 谢谢
I have a list in c#, that list contains structures, I would like to delete repeated structures, but just the structures which have some fields equal.
How Can I do?
thx
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
有两种可能的解决方案:
Hashset
删除重复项。这可以通过自定义IEqualityComparer
来完成(链接) 实现,或者如果您通过使用适当的GetHashCode
和Equals
方法重写实现IEquatable
接口来“拥有”该结构。如果你的集合很小并且这个操作必须在你的代码中完成一次,我会选择解决方案一。但如果一遍又一遍地使用这种比较逻辑,我会选择解决方案二。
解决方案二的实现:
There are two possible solution:
Hashset<YourStruct>
to remove the duplicates. This can be done by a customIEqualityComparer
(link) implementation or if you "own" the struct by implementing theIEquatable
interface with appropriateGetHashCode
andEquals
method overriding.If your set is small and this operation has to be done once in your code, I would go for solution one. But if this comparison logic is used over and over again I would go for solution two.
Implementation for solution two: