Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/338.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/image/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 如何在c语言中对元素列表进行排序_C#_Linq To Xml - Fatal编程技术网

C# 如何在c语言中对元素列表进行排序

C# 如何在c语言中对元素列表进行排序,c#,linq-to-xml,C#,Linq To Xml,我有一个c语言的XElement对象列表。每个XElement对象都有属性索引,如下所示: <A index="2" .... ></A> <B index="4" .....></B> ... .. 但是元素在列表中没有排序。我在这里做错了什么?首先,您没有将值强制转换为int。在这种情况下,这是无害的,但您可能希望执行以下操作: e => (int)e.Attribute("index") 其次,OrderBy不会对其操作的类型产生

我有一个c语言的XElement对象列表。每个XElement对象都有属性索引,如下所示:

<A index="2" .... ></A>
<B index="4" .....></B>
...
.. 

但是元素在列表中没有排序。我在这里做错了什么?

首先,您没有将值强制转换为int。在这种情况下,这是无害的,但您可能希望执行以下操作:

e => (int)e.Attribute("index")
其次,OrderBy不会对其操作的类型产生副作用,但会返回一个新的IEnumerable。您可以通过以下方式覆盖以前的列表:

 listOfElement = listOfElement.OrderBy(e => (int)e.Attribute("index")).
                     ToList();
或者,您可以通过以下方式使用List.SortComparison方法:

listOfElement.Sort((e1, e2) => 
            (int)e1.Attribute("index") - (int)e2.Attribute("index"));

请试一试。

记住,它不是现成的。您正在使用返回值吗?
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;