1

这是我当前的代码,它从 xml 中获取元素并将其放入数组中。但它只是按照它读取它的顺序(从上到下)

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();

我想知道在将数组转换为数组时是否可以按属性(在本例中为“顺序”)对数组进行排序。期望的输出是 {Gragas, Draven, Ryze, Shen, Shyvanna, ...}

这是我的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>

我在玩 OrderBy() 和 OrderByDescending() 时运气不佳

4

1 回答 1

3

使用OrderBy扩展方法

string[] picks = doc
  .Descendants("pick")
  .OrderBy(element => Int32.Parse(element.GetAttribute("order").Value))
  .Select(element => element.Value)
  .ToArray();
于 2013-07-29T23:46:58.650 回答