In the data structure, sorting refers to the arrangement of data in a preferred order. Sorting data makes it easier to quickly and easily search through it.
In this article, I will show you how to sort the custom collection in c#. C# already provides a lot of Sorting API, but let’s suppose that you want to implement our sorting algorithm like bubble or quicksort due to some reason. You can easily do this in C#.
Let’s consider you have the following class Customer
and you want to sort the data by ID using Bubble Sort
The IComparable interface defines a generalized type-specific comparison method that a value type or class can use to order or sort its instances. The type whose value needs to be sorted must implement the IComprable
interface. The interface has one method named, which returns an integer.{alertInfo}
- If the return value is 0 means, both types are equal
- If the return value is 1, then the first type is greater
- If the return value is -1, then the first type is smaller than other
public class Customer
{
public int Id { get; set; }
public string Name { get; set; }
public int CompareTo(Customer other)
{
return this.Id.CompareTo(other.Id);
}
}
public class Customer : IComparable<Customer>
{
public int Id { get; set; }
public string Name { get; set; }
public int CompareTo(Customer other)
{
return this.Id.CompareTo(other.Id);
}
}
As you can in the above class I am comparing Id value. If you want other property then you can use it.
Generic Bubble Sort
Now it's time to implement bubble sort. Its very simple sorting algorithm compares the adjacent value in each pass and moves the largest item to the end.
This algorithm only works on the type who has implemented IComparable
public class BubbleSort<T> where T : IComparable<T>
{
public void Sort(T[] items)
{
for (int i = 0; i < items.Length; i++)
{
for (int j = 0; j < items.Length - 1 - i; j++)
{
if (items[j].CompareTo(items[j + 1]) > 0)
{
var temp = items[j];
items[j] = items[j + 1];
items[j + 1] = temp;
}
}
}
}
}
How to use
void Main()
{
var x = new[] { -1, 2, -2, 10, 4 };
var customers = new Customer[] {
new Customer { Id = 1, Name = "John" },
new Customer { Id = 3, Name = "Joe" },
new Customer { Id = 2, Name = "Aba" },
new Customer { Id = 6, Name = "Bill" },
new Customer { Id = 4, Name = "Steve" },
new Customer { Id = 5, Name = "Raj" }
};
BubbleSort<Customer> bubbleSort = new BubbleSort<Customer>();
bubbleSort.Sort(customers);
Console.WriteLine(customers);
}