Пятница, Ноябрь 27, 2020

List и IComparer

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 DuckComparerBySize : IComparer<Duck>
    {
        public int Compare(Duck x, Duck y)
        {
            if (x.Size < y.Size)
                return -1;
            if (x.Size > y.Size)
                return 1;
            return 0;
        }
    }
    class Program
    {
        public static void PrintDuck(List<Duck> ducks)
        {
            foreach (Duck duck in ducks)
                Console.WriteLine(duck.Size.ToString() + "-дюймов " + duck.Kind.ToString());
            Console.WriteLine("Утки кончились!");
        }
        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=14},
                new Duck(){Kind=KindOfDuck.Decoy,Size=13},
            };
            Console.WriteLine("До сортировки:");
            PrintDuck(ducks);
            Console.WriteLine("После сортировки:");
            DuckComparerBySize sizeComparer = new DuckComparerBySize();
            ducks.Sort(sizeComparer);
            PrintDuck(ducks);
            Console.ReadLine();
        }
    }
}

Back to Top