我有一个C#中的对象列表。每个XElement对象都有属性,类似于以下内容:
<A index="2" .... ></A>
<B index="4" .....></B>
...
..
现在我想按其索引值升序对这些元素进行排序。为此,我尝试了以下操作:
listOfElement.OrderBy(e => e.Attribute("index").Value);
但是列表中的元素没有排序。我在这里做错了什么?
我有一个C#中的对象列表。每个XElement对象都有属性,类似于以下内容:
<A index="2" .... ></A>
<B index="4" .....></B>
...
..
现在我想按其索引值升序对这些元素进行排序。为此,我尝试了以下操作:
listOfElement.OrderBy(e => e.Attribute("index").Value);
首先,您没有将值转换为整数。在这种情况下是无害的,但您可能想要执行以下操作:
e => (int)e.Attribute("index")
OrderBy
不会对其操作的类型进行副作用,而是返回一个新的 IEnumerable<T>
。你可以通过以下方式覆盖先前的列表: listOfElement = listOfElement.OrderBy(e => (int)e.Attribute("index")).
ToList();
或者,您可以使用以下方式中的List<T>.Sort(Comparison<XElement>)
方法:
listOfElement.Sort((e1, e2) =>
(int)e1.Attribute("index") - (int)e2.Attribute("index"));
IEnumerable<XElement> sortShows = from s in listOfElement.Descendants()
orderby (int)s.Attribute("index")
select s;