tags:

views:

61

answers:

2

Hi,

I have a List<> of HTMLAnchor objects (HTMLAnchor is an object from an external API). I want to exclude clicking on some of the links as they are for logging out, etc.

Using LINQ, I can use the Except operator. However, on here (http://msdn.microsoft.com/en-us/vcsharp/aa336761.aspx#except1), the example using the custom type (Product if I remember correctly) does not use the overloaded version of Except.

Furthermore, if I am using a type not defined by me, do the rules change? And should the class I write to implement IEquality have the same name I am trying to exclude in my generic collection (HtmlAnchor)?

Thanks

+1  A: 

When you don't have control over the type, and the default equality operations do not suffice (ie. Equals is not properly implemented), you should use the overload which takes an IEqualityComparer<T> parameter. This is a class that you can implement yourself to provide the definition of equality, that you need.

driis
A: 

If you want to compare anchors using the default Equals method, which in this case will probably give you reference equality, you don't need to do anything: just pass the set of anchors to exclude:

anchors.Except(anchorsToExclude);

If the members of the sequence to exclude will not be reference-equal (or whatever HtmlAnchor.Equals deems equal), the interface you want to implement is IEqualityComparer<T>. This exists precisely to allow you to provide a custom equality comparison for a type that you don't define, so the rules don't change -- you just have to use the appropriate overload of Except.

So you would create a class called e.g. HtmlAnchorEqualityComparer which implements IEqualityComparer<HtmlAnchor>, and pass an instance of that to Except:

anchors.Except(anchorsToExclude, new HtmlAnchorEqualityComparer())
itowlson