I have a list of XElement Objects in c#. Each XElement object has attribute index, something like this :
<A index="2" .... ></A>
<B index="4" .....></B>
...
..
Now i want to sort these elements in ascending order according to its index value. For this i tried :
listOfElement.OrderBy(e => e.Attribute("index").Value);
But the elements are not sorted in the list. What i am doing wrong here ?
First, you’re not casting the value to an int. It’s harmless in this case, but you might want to do:
Secondly, the
OrderBydoesn’t do side-effect on the type it operates on, but it returns a newIEnumerable<T>. You can overwrite your previous list by writing:Alternatively, you can use the
List<T>.Sort(Comparison<XElement>)method in this way: