Sorting the item in collection is very easy
steps, simply call Sort() method on the collection and item will be
sorted .
But this Sort() method only works for primitive
type of collection (example int, decimal etc.).
Here is an example of sorting a collection of
integer items
List<int> collections = new List<int> { 34, 3, 54, 5, 74, 14, 425 };
Iterates the items and see original item order
Console.WriteLine("Before Sorting");
foreach (int item in collections)
{
Console.WriteLine(item);
}
Output:
After calling sort () method on collection
Console.WriteLine("After Sorting");
collections.Sort();
foreach (int item in collections)
{
Console.WriteLine(item);
}
Output:
By
using IComparable interface
When you want to sort the custom object, you
have to implement IComparable interfere which allows custom sorting of objects when
implemented. When a class implements this interface, we must add the public
method CompareTo(T). We implement custom sorting for a class with IComparable.
Here is a custom object StateInfo, which uses
IComparable interface for sorting:
public class StateInfo : IComparable<StateInfo>
{
public string contact;
public DateTime date;
public string action;
public int CompareTo(StateInfo value)
{
return this.date.CompareTo(value.date);
}
}
As per above code, by default sorting will be
'date' field, if you want to sorting
based on contact instead of date then modify above CompareTo function code
public int CompareTo(StateInfo value)
{
return this.contact.CompareTo(value.contact);
}
Main Programming Code:
private static void
ArraySort()
{
var _allStatInfo = new List();
_allStatInfo.Add(new StatInfo { contact = "HCL", date = DateTime.Today,
action = "PUT" });
_allStatInfo.Add(new StatInfo { contact = "TCS", date =
DateTime.Today.AddDays(3), action = "POST" });
_allStatInfo.Add(new StatInfo { contact = "Infy", date =
DateTime.Today.AddDays(-5), action = "GET" });
_allStatInfo.ForEach(x => Console.WriteLine(x.contact));
// this now sorts by date
_allStatInfo.Sort();
_allStatInfo.ForEach(x => Console.WriteLine(x.contact));
}
By using Delegate to Anonymous
Method:
In C#, we can also sort the collection of
custom object with help of Delegate/Anonymous method
var arr =
_allStatInfo.ToArray();
Array.Sort(arr, delegate (StatInfo a, StatInfo b)
{
return a.date.CompareTo(b.date);
});
Other Links:
Thanks for Visiting!!