且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

从对象列表中删除重复项

更新时间:2022-12-12 08:44:06

如果您要寻找的是速度,并且不介意占用一些内存,那么我建议您使用HashSet有兴趣进行自定义比较的用户,则可以制作一个IEqualityComparer<T>,如下所示:

If what you are looking for is speed, and don't mind using up some memory then I would recommend that you use a HashSet, if you are interested in doing some custom comparison, then you can make an IEqualityComparer<T>, something like this:

var original = new ArrayList(); // whatever your original collection is 
var unique = new HasSet<YourClass>(new MyCustomEqualityComparer());

foreach(var item in original)
{
    if(!unique.Contains(item))
        unique.Add(item);
}

return unique;

这里的问题是,您最终可能会吞噬原始内存的两倍.

the issue here is that you may end up gobbling up twice the original memory.

我做了一些额外的研究,我认为您只需做以下即可达到您想要的目标:

I made some extra research and I think you can achieve just what you want by simply doing:

var original // your original data
var unique = new HashSet<YourClass>(origin, new CustomEqualityComparer());

应该注意删除重复的数据,因为HashSet不允许重复.我建议您还看看关于GetHasCode实施指南的问题.

that should take care of removing duplicated data as no duplication is allowed in a HashSet. I'd recommend that you also take a look at this question about GetHasCode implementation guidelines.

如果您想进一步了解HashSet类,请遵循以下链接:

If you want to know some more about the HashSet class follow these links:

关于HashSet
关于IEqualityComparer构造函数
IEqualityComparer文档

About HashSet
About IEqualityComparer constructor
IEqualityComparer documentation

希望这会有所帮助