Понедельник, Май 25, 2020

List и IComparable

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication2
{
    enum KindOfDuck
    {
        Mallard,Muscovy,Decoy,
    }
    class Duck:IComparable<Duck>
    {
        public KindOfDuck Kind;
        public int Size;
        public int CompareTo(Duck duckToCompare)
        {
            if (this.Size > duckToCompare.Size)
                return 1;
            else if (this.Size < duckToCompare.Size)
                return -1;
            else
                return 0;
        }
    }
    class Program
    {
        static void Main(string[] args)
        {
            List<Duck> ducks = new List<Duck>(){
                new Duck(){Kind=KindOfDuck.Mallard,Size=17},
                new Duck(){Kind=KindOfDuck.Muscovy,Size=18},
                new Duck(){Kind=KindOfDuck.Decoy,Size=14},
                new Duck(){Kind=KindOfDuck.Muscovy,Size=11},
                new Duck(){Kind=KindOfDuck.Mallard,Size=15},
                new Duck(){Kind=KindOfDuck.Decoy,Size=13},
            };
            Console.WriteLine("До сортировки:\n");
            foreach (Duck d in ducks)
                Console.WriteLine(d.Size.ToString());

            ducks.Sort();

            Console.WriteLine("После сортировки:\n");
            foreach (Duck d in ducks)
                Console.WriteLine(d.Size.ToString());
            Console.ReadLine();
        }
    }
}

Back to Top