Implement IComparable to use List.Sort : List « Data Structure « C# / CSharp Tutorial






using System;
using System.Collections.Generic;

    public class Employee : IComparable<Employee>
    {
        private int empID;

        public Employee(int empID)
        {
            this.empID = empID;
        }

        public override string ToString()
        {
            return empID.ToString();
        }

        public bool Equals(Employee other) 
        {
            if (this.empID == other.empID)
            {
                return true;
            }
            else
            {
                return false;
            }
        }
        public int CompareTo(Employee rhs)
        {
            return this.empID.CompareTo(rhs.empID);
        }
    }
    public class Tester
    {
        static void Main()
        {
            List<Employee> empArray = new List<Employee>();
            List<Int32> intArray = new List<Int32>();

            for (int i = 0; i < 5; i++)
            {
                empArray.Add(new Employee(i));
                intArray.Add(i);
            }
            intArray.Sort();
            for (int i = 0; i < intArray.Count; i++)
            {
                Console.Write("{0} ", intArray[i].ToString());
            }
            empArray.Sort();
            for (int i = 0; i < empArray.Count; i++)
            {
                Console.Write("{0} ", empArray[i].ToString());
            }
        }
    }








11.34.List
11.34.1.Obtaining a read-only copy of a list
11.34.2.Using the Action delegate
11.34.3.Converting a list from list of string to list of int
11.34.4.Converting a list: user defined converting function
11.34.5.Vector extends List
11.34.6.List Filtering With Linq
11.34.7.List Joining Ordering And Filtering With Linq
11.34.8.List Order With Extension Method
11.34.9.List Query With Delegates
11.34.10.List Query With Delegates Compact
11.34.11.List Query With Lambda Expression
11.34.12.List Sort With Comparer
11.34.13.List Sort With Comparison Delegate
11.34.14.Implement IComparable to use List.Sort
11.34.15.List.ForEach
11.34.16.Compact Code for looping through the List with delegate
11.34.17.List Convert All
11.34.18.Using external method to pass into Find method
11.34.19.List size and capacity
11.34.20.List range operation
11.34.21.Use Action<(Of <(T>)>) delegate to print the contents of a List<(Of <(T>)>) object.
11.34.22.Item property (the indexer in C#) and various other properties and methods of the List<(Of <(T>)>) generic class.