score:1

Accepted answer

You could just create an IEqualityComparer to use with the Distinct(), that should get you what you need.

class Program
{
    static void Main(string[] args)
    {
        string xml = "<foo><property name=\"John\" value=\"Doe\" id=\"1\"/><property name=\"Paul\" value=\"Lee\" id=\"1\"/><property name=\"Ken\" value=\"Flow\" id=\"1\"/><property name=\"Jane\" value=\"Horace\" id=\"1\"/><property name=\"Paul\" value=\"Lee\" id=\"1\"/></foo>";

        XElement x = XElement.Parse(xml);
        var a = x.Elements().Distinct(new MyComparer()).ToList();
    }
}

class MyComparer : IEqualityComparer<XElement>
{
    public bool Equals(XElement x, XElement y)
    {
        return x.Attribute("name").Value == y.Attribute("name").Value;
    }

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

score:1

Your appoach is a bit weird, e.g., You don't need to project elements into new elements; it just works(tm) when you add existing elements to a new document.

I would simply group the <property> elements by the name attribute and then select the first element from each group:

var doc = XDocument.Parse(@"<foo>...</foo>");

var result = new XDocument(new XElement("foo",
    from property in doc.Root
    group property by (string)property.Attribute("name") into g
    select g.First()));

score:1

I think you should remove the duplicates first, and then do your projection. For example:

var uniqueProps = from property in doc.Root
                  group property by (string)property.Attribute("name") into g
                  select g.First() into f
                  select new XElement("property", 
                      new XAttribute("name", f.Attribute("name").Value),
                      f.Attribute("value"));

or, if you prefer method syntax,

var uniqueProps = doc.Root
    .GroupBy(property => (string)property.Attribute("name"))
    .Select(g => g.First())
    .Select(f => new XElement("property", 
                     new XAttribute("name", f.Attribute("name").Value),
                     f.Attribute("value")));

Related Articles