Implement a Comparable Type - CSharp Custom Type

CSharp examples for Custom Type:interface

Description

Implement a Comparable Type

Demo Code


using System;//from ww w  . j  a v  a  2  s.  c  om
using System.Collections.Generic;

    public class Newspaper : IComparable<Newspaper>
    {
        private string name;
        private int circulation;

        private class AscendingCirculationComparer : IComparer<Newspaper>
        {
            public int Compare(Newspaper x, Newspaper y)
            {
                if (x == null && y == null) return 0;
                else if (x == null) return -1;
                else if (y == null) return 1;

                if (x == y) return 0;

                return x.circulation - y.circulation;
            }
        }
        public Newspaper(string name, int circulation)
        {
            this.name = name;
            this.circulation = circulation;
        }
        public static IComparer<Newspaper> CirculationSorter
        {
            get { return new AscendingCirculationComparer(); }
        }

        public override string ToString()
        {
            return string.Format("{0}: Circulation = {1}", name, circulation);
        }

        public int CompareTo(Newspaper other)
        {
            if (other == null) return 1;

            if (other == this) return 0;
            return string.Compare(this.name, other.name, true);
        }
    }

class MainClass
    {
        public static void Main()
        {
            List<Newspaper> newspapers = new List<Newspaper>();

            newspapers.Add(new Newspaper("A", 1));
            newspapers.Add(new Newspaper("B", 5));
            newspapers.Add(new Newspaper("C", 2));
            newspapers.Add(new Newspaper("D", 8));
            newspapers.Add(new Newspaper("E", 5));

            Console.WriteLine("Unsorted newspaper list:");
            foreach (Newspaper n in newspapers)
            {
                Console.WriteLine("  " + n);
            }

            Console.WriteLine("Newspaper list sorted by name (default order):");
            newspapers.Sort();
            foreach (Newspaper n in newspapers)
            {
                Console.WriteLine("  " + n);
            }

            Console.WriteLine("Newspaper list sorted by circulation:");
            newspapers.Sort(Newspaper.CirculationSorter);
            foreach (Newspaper n in newspapers)
            {
                Console.WriteLine("  " + n);
            }

        }
    }

Result


Related Tutorials