C# 检查对象数组是否重复
我有一个 Customer[] 对象数组,我想用它来创建一个 Dictionary
I have an array of Customer[] objects, and I want to use it to create a Dictionary<Customer, string>. What is the easiest way to examine the array for duplicates before I load the Dictionary? I want to avoid "ArgumentException: An item with the same key has already been added". Thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
只需在添加客户之前调用 Dictionary.ContainsKey(key) 即可。
Just call Dictionary.ContainsKey(key) before you add your Customers.
您可以使用 LINQ 来完成这两件事:
如果您将以不太简单的方式构建字典,则可以使用
Distinct()
扩展方法来获取唯一的数组,如下所示:如果您需要意识到潜在的重复项,您可以首先使用
GroupBy( c => c )
来识别哪些项目有重复项。最后,如果您不想使用 LINQ,您可以动态构建字典并在添加每个项目时使用前置条件检查:
You could use LINQ to do both:
If you will build the dictionary in a less straightforward fashion, you can just use the
Distinct()
extension method to get a unique array like so:If you need to be aware of potential duplicates, you could use
GroupBy( c => c )
first to identify which items have duplicates.Finally, if you don't want to use LINQ, you can build the dictionary on the fly and use a precondition check when adding each item:
从性能和代码的角度来看,最有效的方法是:这样,
您提到的异常将永远不会被抛出,并且键查找不会发生两次
The most efficient way of doing that, from BOTH PERFORMANCE and CODE points of view, is this:
This way the exception mentioned by you will never get thrown, and the key lookup will not happen twice
数组有多大?出现重复的可能性有多大?
将数组的每个元素与所有其他元素进行检查是一项相当昂贵的操作。
在添加每个项目之前调用
Dictionary.ContainsKey(key)
会更快。注意:如果重复很少见,那么您可以使用异常处理,但这是不好的编程习惯。
How big is the array? and how likely is it that there will be duplicates?
Checking each element of the array against all the others is quite a expensive operation.
It would be quicker to call
Dictionary.ContainsKey(key)
before adding each item.NOTE: If duplicates are rare then you could use exception handling, but that's bad programming practice.
在这种情况下,您对重复的定义是什么?
如果它只是相同的对象实例(相同的指针)那么这很简单,您可以使用此处给出的其他答案中的任何方法。
有时,尽管相等的概念并不那么简单,但具有相同数据的不同对象实例是否相等?在这种情况下,您可能需要 IEqualityComparer 的实现来帮助您。
What is your definition of duplicate in this case?
If its simply the same object instance (the same pointer) then that's simple, you can use any of the methods in the other answers given here.
Sometimes though the concept of equality is not so straight forward, is a different object instance with the same data equal? In that case you probably want an implementation of an IEqualityComparer to help you.
为什么不是这个?
Why not this??