Game Development Reference
In-Depth Information
Classified intel
In this section, we used the IComparable<T> generic interface to create a custom sort-
ing method to sort the generic List<T> objects. We know that the generic List<T> ob-
jects are similar to ArrayList , except with the specific type; in this case, UserData .
To be able to order List<T> , we will call the List<T>.Sort() method. This method
will automatically call the CompareTo() function, which is the method in ICompar-
able<T> . This method is used to compare the value between two objects, which will re-
turn only three values (less than 0 or -1, 0, greater than 0 or 1). The value less than 0 means
the first object is less than other object. 0 means both objects are equal. Then the value
greater than 0 means the first object is greater than other object.
In the Hiscore script in SortByScore() , we will see that we used the Sort() func-
tion for _users , which is the List<UserData>() array. The Sort() method uses
the default comparer, Comparer<T>.Default , for type T to determine the order of the
list elements. Then, the Comparer<T>.Default property will check whether or not the
IComparable<T> generic interface is implemented, which we already implemented in
our UserData script.
The result from the sorting method will return _users from the lowest score to the
highest score. So, we use the Reverse() function to reverse the result, which will give
_users order from the highest to the lowest score.
Note
List<T> is in the .NET framework class library. We might want to check out the follow-
ing MSDN Microsoft library links:
• For more information about the List<T> method, visit ht-
tp://msdn.microsoft.com/en-us/library/s6hkc2c4(v=vs.110).aspx .
• For more information about the Sort() method, visit http://msdn.microsoft.com/
en-us/library/b0zbh7b6(v=vs.110).aspx .
• For more information about the Comparer<T> class and example, visit ht-
tp://msdn.microsoft.com/en-us/library/azhsac5f(v=vs.110).aspx .
• For more information about the IComparable<T> interface and the Com-
pareTo() method, visit the following links: http://msdn.microsoft.com/en-us/lib-
Search WWH ::




Custom Search