LINQ and Distinct method and custom IEqualityComparer

M

Martin Honnen

I am playing with Visual Studio 2008 and LINQ to XML.

When trying to use the Distinct method with a custom class implementing
IEqualityComparer<XElement> I can't compile the project which I do not
understand. Maybe someone here can tell me what I am doing wrong.

Here comes the full source code:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Linq;

namespace ConsoleApplication2
{
class Program
{
static void Main(string[] args)
{
XElement el = XElement.Load(@"..\..\XMLFile1.xml");
foreach (XElement item in el.Elements("item").Distinct(new
MyComparer<XElement>()))
{
Console.WriteLine(item.Value);
}
}
}

public class MyComparer<XElement> : IEqualityComparer<XElement>
{
#region IEqualityComparer<XElement> Members

public bool Equals(XElement x, XElement y)
{
return x.Value == y.Value;
}

public int GetHashCode(XElement obj)
{
return obj.Value.GetHashCode();
}

#endregion
}
}

The compiler flags three errors, all related to the attempts to try to
use the Value property of XElement objects in the MyComparer class,
error message is the following:
"Error 1 'XElement' does not contain a definition for 'Value' and no
extension method 'Value' accepting a first argument of type 'XElement'
could be found (are you missing a using directive or an assembly
reference?) C:\Dokumente und Einstellungen\Martin Honnen\Eigene
Dateien\Visual Studio
2008\Projects\ConsoleApplication2\ConsoleApplication2\Program.cs 27 22
ConsoleApplication2
"

I have references to System.Xml and System.Xml.Linq in the project so I
don't understand why the code does not compile as XElement has a
property named Value (documented here
<URL:http://msdn2.microsoft.com/en-us/library/System.Xml.Linq.XElement.Value(VS.90).aspx>)
and item.Value in the Main method compiles just fine.
 
J

Jon Skeet [C# MVP]

Martin Honnen said:
I am playing with Visual Studio 2008 and LINQ to XML.

When trying to use the Distinct method with a custom class implementing
IEqualityComparer<XElement> I can't compile the project which I do not
understand. Maybe someone here can tell me what I am doing wrong.

Here comes the full source code:

public class MyComparer<XElement> : IEqualityComparer<XElement>

This bit is the problem. You've declared it as a generic class, with
XElement as a type parameter - it should be:

public class MyComparer : IEqualityComparer<XElement>

(and ditch the type argument when constructing an instance).

Interesting bug though - it took me quite a while to spot what was
going on!
 

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

Top