Thursday, September 2, 2010

Sort Lists

Lists are represented by the type List<T> in the .Net framework, whereby T denotes any type, meaning lists can be typified, so that they accept only objects of one type to grant data consistence.
In this post I will explain how to sort lists, in the previous post I had shown how to sort arrays. Since I started explaining sorting there, this post will be slightly shorter.
As explained there for arrays the static function Array.Sort() was used, for lists the instance function has to be used. That means, that for arrays we could use the function of the not instanced class Array, for lists we have to call this function of a instance of the class List, so for example MyCreatedList.Sort().
The following source code sorts the list TestList in decreasing order:

List<int> TestList = new List<int>(){5, 1, 2, 4, 3}; // short way to initialize and fill lsits
TestList.Sort(); // sort the list increasing
TestList.Reverse(); // reverses the order of the elements

No comments:

Post a Comment