Sorting Arrays [C#]
This example shows how to sort arrays in C#. Array can be sorted using static method Array.Sortwhich internally use Quicksort algorithm.
Sorting array of primitive types
To sort array of primitive types such as int, double or string use method Array.Sort(Array) with the array as a paramater. The primitive types implements interface IComparable, which is internally used by the Sort method (it calls IComparable.CompareTo method). See example how to sort int array:
[C#]
int[] intArray = new int[5] { 8, 10, 2, 6, 3 };
Array.Sort(intArray);
foreach (int i in intArray) Console.Write(i + " ");
or how to sort string array:
[C#]
string[] stringArray = new string[5] { "X", "B", "Z", "Y", "A" };
Array.Sort(stringArray);
foreach (string str in stringArray) Console.Write(str + " ");
Sorting array of custom type using delegate
To sort your own types or to sort by more sophisticated rules, you can use delegate to anonymous method. The generic delegate Comparison<T> is declared as public delegate int Comparison<T> (T x, T y)
. It points to a method that compares two objects of the same type. It should return less then 0 when X < Y, zero when X = Y and greater then 0 when X > Y. The method (to which the delegate points) can be also an anonymous method (written inline).
Following example demonstrates how to sort an array of custom type using the delegate to anonynous comparison method. The custom type in this case is a class User with properties Name and Age.
[C#]
User[] users = new User[3] { new User("Betty", 23),
new User("Susan", 20),
new User("Lisa", 25) };
[C#]
Array.Sort(users, delegate(User user1, User user2) {
return user1.Name.CompareTo(user2.Name);
});
foreach (User user in users) Console.Write(user.Name + user.Age + " ");
[C#]
Array.Sort(users, delegate(User user1, User user2) {
return user1.Age.CompareTo(user2.Age);
});
foreach (User user in users) Console.Write(user.Name + user.Age + " ");
Sorting array using IComparable
If you implement IComparable interface in your custom type, you can sort array easily like in the case of primitive types. The Sort method calls internally IComparable.CompareTo method.
[C#]
public class User : IComparable
{
public int CompareTo(object obj)
{
if (obj is User) {
return this.Name.CompareTo((obj as User).Name);
}
throw new ArgumentException("Object is not a User");
}
}
Use it as you sorted the primitive types in the previous examples.
[C#]
Array.Sort(users);
출처 : http://www.csharp-examples.net/sort-array/