iequalitycomparer help

  • Thread starter Thread starter psawant
  • Start date Start date
P

psawant

Hi all,

I have a custom colllelctoin class which inherits collecton base.
It is a collecton of objects of type X and X has ID integer as like a
unique key.

How do i check if the object already exists in the collection?.

I think i am missing something straightfoward.

Thanks for your input.
 
Hi,

If your object derives from System.Collections.CollectionBase then you'll have
to iterate the entire collection and compare each item individually.

You could do something like this instead:

public class XCollection : List<X>
{
public bool Exists(X x)
{
return Exists(delegate(X x1)
{
return x.ID == x1.ID;
});
}
}

If your object is more like a value-type, then make it an immutable struct and
override the Equals method. Then you'll be able to use X in lists as if it
were the ID that it contains - meaning you won't need to use the code above at
all. If you make a struct then you should also override GetHashCode and
create operator overloads for == and != as well:
 
Hi,

I just realized that you mentioned ID is an integer, which means you might be
able to increase the performance of the search by using List<X> and calling
Sort, then BinarySearch and supplying to both a custom IComparer<X>
implementation that compares on the ID property. You could modify my
XCollection example to encapsulate that functionality in Exists(X), for
instance. Then you probably shouldn't derive from List<X> but instead
composite it.

HTH
 
Back
Top