web analytics

IComparable, IComparable<T>, IComparer and IComparer<T> in C#

Options
@2016-02-24 20:12:47

List<T>.Sort(Comparison<T>) Method

The List<T>.Sort(Comparison<T>) method sorts the elements in the entire List<T> using the specified System.Comparison<T>.

The following code example demonstrates the use of the Comparison<T> delegate with the Sort(Comparison<T>) method overload.

public class Employee
{
    private string _id;
    private string _name;
    private int _age;
    private double _salary;


    public string ID
    {
        get
        {
            return this._id;
        }
    }
    public string Name
    {
        get
        {
            return this._name;
        }
    }

    public int Age
    {
        get
        {
            return this._age;
        }
    }
    public double Salary
    {
        get
        {
            return this._salary;
        }
    }

    public Employee(string id, string name, int age, double salary)
    {
        this._id = id;
        this._name = name;
        this._age = age;
        this._salary = salary;
    }
    public override string ToString()
    {
        return string.Format("[ID: {0}, Name: {1}, Age: {2}, Salary: {3}]", 
                              this._id, this._name, this._age, this._salary);
    }
}


class Program
{
 private static int CompareEmployee(Employee x, Employee y)
  {
      if (x == null)
      {
          if (y == null)
          {
              // If x is null and y is null, they're
              // equal.
              return 0;
          }
          else
          {
              // If x is null and y is not null, y
              // is greater.
              return -1;
          }
      }
      else
      {
          // If x is not null...
          //
          if (y == null)
              // ...and y is null, x is greater.
          {
              return 1;
          }
          else
          {
              return x.ToString().CompareTo(y.ToString());
          }
      }
  }

  static void Main(string[] args)
  {
      List<Employee> employeeList = new List<Employee>();
      employeeList.Add(new Employee("100", "Derrel Brill", 22, 53000));
      employeeList.Add(new Employee("300", "Dave Gate", 30, 60000));
      employeeList.Add(new Employee("200", "Jimmy Renaud", 55, 80000));


      employeeList.Sort(CompareEmployee);

      foreach (Employee e in employeeList)
      {
          Console.WriteLine(e.ToString());
      }
 }
}

Comments

You must Sign In to comment on this topic.


© 2024 Digcode.com