By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
454,982 Members | 1,114 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 454,982 IT Pros & Developers. It's quick & easy.

check for duplicates

P: n/a
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
May 19 '06 #1
Share this Question
Share on Google+
2 Replies


P: n/a
"Peter Kirk" <pk@alpha-solutions.dk> skrev i en meddelelse
news:uE**************@TK2MSFTNGP04.phx.gbl...
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
May 19 '06 #2

P: n/a
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
May 19 '06 #3

This discussion thread is closed

Replies have been disabled for this discussion.