Search code examples
c#xmllinqicomparer

Sort/orderby nodes in xml using IComparer


I need to sort nodes in xml. I have the following code which successfully orders them alphabetically. However, much of the data is numeric although strings are allowed. I have a IComparer set up that works to correctly sort data as I wish it to appear elsewhere.

System.Xml.Linq.XDocument output = new System.Xml.Linq.XDocument(
                    new System.Xml.Linq.XElement("xml",
                from node in input.Root.Elements("training")
                orderby node.Attribute("order").Value
                select node));

I've found how to use an IComparer in a method call, .OrderBy(x => x, new CustomComparer()) But, I haven't figured out how to get that to work with the xml. From what I've read online, it doesn't look like I can call an IComparer from the query syntax.


Solution

  • You're right, you can't use that overload from a query expression orderby clause. Fortunately, your query is pretty simple, so you can just use:

    // Have a using directive for System.Xml.Linq - it'll make everything simpler!
    XDocument output = new XDocument(
        new XElement("xml",
            input.Root
                 .Elements("training")
                 .OrderBy(node => node.Attribute("order)".Value, comparer)));