List<T> class has a Sort() method which sorts the elements in the entire List<T> using the default comparer. (<T> => , ...)
List<string> strList = new List<string>();
strList.Add("Ss");
strList.Add("As");
strList.Add("Rs");
strList.Add("Ks");
strList.Sort();
foreach (string item in strList)
{
Console.WriteLine(item);
}
IComparable - Sorting list of
complex type like List<Employee> using IComparable and only by one way.
public class Employee
{
public string Name { get; set; }
public int Age { get; set; }
}
List<Employee> employee = new List<Employee>();
employee.Add(new Employee() { Name = "Ss", Age =
30 });
employee.Add(new Employee() { Name = "As", Age =
25 });
employee.Add(new Employee() { Name = "Rs", Age =
20 });
employee.Add(new Employee() { Name = "Ks", Age =
30 });
employee.Add(new Employee() { Name = "Av", Age =
50 });
employee.Sort();
foreach (Employee item in employee)
{
Console.WriteLine("{0},
{1}", item.Name, item.Age);
}
So in order to do this we will have to implement Employee class by IComparable. and have to put sorting logic in implemented function CompareTo.
public class Employee : IComparable<Employee>
{
public string Name { get; set; }
public int Age { get; set; }
public int CompareTo(Employee other)
{
if (this.Age == other.Age)
{
return this.Name.CompareTo(other.Name);
}
return this.Age.CompareTo(other.Age);
}
}
IComparer - Used to sorting
list of complex type using IComparer and by multiple ways like Name or by Age.
public class Employee
{
public string Name { get; set; }
public int Age { get; set; }
}
public class SortEmployeeByName : IComparer<Employee>
{
public int Compare(Employee x, Employee y)
{
return string.Compare(x.Name, y.Name);
}
}
public class SortEmployeeByAge : IComparer<Employee>
{
public int Compare(Employee x, Employee y)
{
if (x.Age == x.Age)
{
return 0;
}
if (x.Age > y.Age)
{
return 1;
}
if (x.Age < y.Age)
{
return -1;
}
return 0;
}
}
List<Employee> employee = new List<Employee>();
employee.Add(new Employee() { Name = "Ss", Age =
35 });
employee.Add(new Employee() { Name = "As", Age =
25 });
employee.Add(new Employee() { Name = "Rs", Age =
20 });
employee.Add(new Employee() { Name = "Ks", Age =
30 });
employee.Add(new Employee() { Name = "Av", Age =
50 });
//---------------
Console.WriteLine("By Name
....");
employee.Sort(new SortEmployeeByName());
foreach (Employee item in employee)
{
Console.WriteLine("{0},
{1}", item.Name, item.Age);
}
//---------------
Console.WriteLine("By Age
....");
employee.Sort(new SortEmployeeByAge());
foreach (Employee item in employee)
{
Console.WriteLine("{0},
{1}", item.Name, item.Age);
}