1

Here is my current code that gets the elements from the xml and puts it into an array. But it just puts it in the order it reads it (top to bottom)

using System.Xml;
using System.Xml.Linq;

// XML Path
var doc = XDocument.Load("C:/Scripts/example.xml");

// Node
string[] picks = doc.Descendants("pick").Select(element => element.Value).ToArray();

I want to know if it is possible to sort the array by an attribute (in this case, "order") as I turn it into an array. The desired output being {Gragas, Draven, Ryze, Shen, Shyvanna, ...}

here's my xml:

<championSelect>
<blue>
  <pick order="1">Gragas</pick>
  <pick order="4">Shen</pick>
  <pick order="5">Shyvanna</pick>
  <pick order="8">Garen</pick>
  <pick order="9">Karthus</pick>
</blue>
<red>
  <pick order="2">Draven</pick>
  <pick order="3">Ryze</pick>
  <pick order="6">Ahri</pick>
  <pick order="7">Annie</pick>
  <pick order="10">Brand</pick>
</red>

I was playing with OrderBy() and OrderByDescending() with little luck

3
  • Why not use OrderBy before .ToArray? Commented Jul 29, 2013 at 23:43
  • Turn it into an array then sort it. It makes a lot more sense to sort an array than it does to sort XML (which might be possible using some abstraction like LINQ to XML but isn't noramlly and doesn't make sense). Commented Jul 29, 2013 at 23:43
  • @evanmcdonnal turning it into an array first won't work here because the OP wants to sort on a value which won't be in the final array Commented Jul 29, 2013 at 23:52

1 Answer 1

3

Use the OrderBy extension method

string[] picks = doc
  .Descendants("pick")
  .OrderBy(element => Int32.Parse(element.GetAttribute("order").Value))
  .Select(element => element.Value)
  .ToArray();
Sign up to request clarification or add additional context in comments.

6 Comments

+1 but it should be OrderBy(element => Int32.Parse(element.Attribute("order").Value) I think.
@keyboardP i believe i'm correct. The GetAttribute method returns ` string` while GetAttributeNode returns a AttributeNode type. On that method I would need to call Value.
@keyboardP here is the MSDN page msdn.microsoft.com/en-us/library/acwfyhc7.aspx
element is of type XElement and not XmlElement as Descendants returns XElements.
@keyboardP ah yes you are correct. I was reading XmlDocument and not XDocument. I will update
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.