S_pot

C#_iComparable인터페이스: 비교정렬 본문

C#

C#_iComparable인터페이스: 비교정렬

S_pot 2021. 6. 4. 11:31

 

namespace _210604_004
{   // iComparable 인터페이스
   // 정렬하기 위해서는 IComparable을 상속받아야 하고
    // CompareTo메서드를 생성해주어야 한다.
    class Program
    {
        class Product : IComparable // 자동으로 메서드 생성가능
    {
        public string Name { get; set; }
        public int Price { get; set; }

            // Name으로 비교정렬
           public int CompareTo(object tttt)     // 비교메서드를 입력해주어야 한다.
            {              
                return this.Name.CompareTo(((Product)tttt).Name);   // 이름순으로 정렬               
            }
            
             // Price로 비교정렬
          /* public int CompareTo(object tttt)     // 비교메서드를 입력해주어야 한다.
            {
                //return = this.Price - ((Product)tttt).Price; // 가격순서대로 정렬
                return ((Product)tttt).Price - this.Price;   // 역순으로 정렬
               // return Temp;        
            } */

            public override string ToString()
        {
            return Name + " : " + Price + "원";

        }
         
        }
        static void Main1(string[] args)
        {
            List<int> list = new List<int>() {132,9647,1894,784 };            
            list.Sort();     // Sort 정렬해줌, <int>형이므로 숫자순으로 자동으로 정렬해줌

            foreach (var item in list)
            {
                Console.WriteLine(item);
            }
        }

        static void Main(string[] args)
        {
            List<Product> list = new List<Product>()
            {
                new Product() { Name = "고구마", Price = 1500},
                new Product() { Name = "사과", Price = 2400},
                new Product() { Name = "바나나", Price = 1000},
                new Product() { Name = "배", Price = 3000},
            };
            list.Sort();   // <Product>는 자동으로 기준점을 정하지 못해 정렬하지 못하고 에러가 발생

            foreach (var item in list)
            {
                Console.WriteLine(item);
            }
        }
    }
}