문제

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.

도움이 되었습니까?

해결책

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)));
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top