check for duplicates

  • Thread starter Thread starter Peter Kirk
  • Start date Start date
P

Peter Kirk

Hi

if I have a List<MyObject> of MyObject objects, what is the best way to
check for duplicates? (By "duplicate" I mean that MyObject has a property
called "name" for example, which I want to check if this value appears more
than once in the list of MyObjects).

Thanks,
Peter
 
Peter Kirk said:
if I have a List<MyObject> of MyObject objects, what is the best way to
check for duplicates? (By "duplicate" I mean that MyObject has a property
called "name" for example, which I want to check if this value appears
more than once in the list of MyObjects).

Hi again - anyone know of some good web-resources which describe best
practices for overriding Equals and GetHashCode?

Thanks,
Peter
 
What I would do is create a Dictionary<string, MyObject>, and then something
like (not tested)
Dictionary<string, MyObject> uniqueSet = new Dictionary<string, MyObject>();
foreach(MyObject obj in originalList> {
string name = obj.Name;
if(uniqueSet.ContainsKey(name)) {
// whoops! we have a duplicate (against uniqueSet[name])
} else {
uniqueSet.Add(name, obj);
}
}

Note that if you want to see what it conflicts with, then the following is
more efficient:
MyObject conflict;
if(uniqueSet.TryGetValue(name, out conflict)) {
// conflicts against conflict
} else {
uniqueSet.Add(name, obj);
}

Marc
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Back
Top