[C#] IComparable / IEnumerable

타키탸키·2022년 1월 10일
0

C언어(C, C++, C#)

목록 보기
12/14
  • C#의 컬렉션은 대부분 Sort 메서드를 제공
    • IComparable 인터페이스 기반의 요소를 보관할 때 정상 동작
    • 그 외에는 예외 발생
  • C#의 System에 정의되어 있는 기본 형식들은 IComparable 인터페이스를 기반으로 정의
    • 기본 형식으로 보관한 컬렉션은 Sort 메서드를 이용하여 정렬 가능
  • 추상 클래스 Array의 정적 메서드 Sort
    • 1차원 배열 정렬 가능
int[] arr = new int[5] {3,4,8,1,6};

Array.Sort(arr);

foreach (int i in arr)
{
  Console.Write("{0} ",i);
}
Console.WriteLine();
1 3 4 6 8
  • 리스트에서의 활용
using System;
using System.Collections.Generic;

class Example : IComparable<Example>
{
  public int a;
  
  public int CompareTo(Example other)
  {
    return this.a - other.a;
  }
}

class Program
{
  static void Main(string[] args)
  {
    Example ex = new Example();
    List<Example> examples = new List<Example>();
    examples.Add(new Example() {a=0});
    examples.Add(new Example() {a=-2});
    examples.Sort();
    
    foreach(Example example in examples)
    {
      Console.Write(example.a + " "); // -2 0
    }
 }
  • C#의 모든 컬렉션은 IEnumerable을 상속 받아 구현하고 있다
    • 따라서, List와 Array 같은 컬렉션 객체들을 foreach문을 통해 돌릴 수 있다
  • IEnumerable
    • 열거자(IEnumerator)를 Get하는데 필요한 인터페이스
using System;
using System.Collections.Generic;

class Example : IComparable<Example>
{
  public int a;
  
  public int CompareTo(Example other)
  {
    return this.a - other.a;
  }
}

class Program
{
  static void Main(string[] args)
  {
    Example ex = new Example();
    List<Example> examples = new List<Example>();
 
    foreach(Example example in GetExList())
    {
      Console.Write(example.a + " "); // 0 1 2 3 4 5 6 7 8 9
    }
  }
  
  public static IEunmerable<Exmaple> GetExList()
  {
  for(int i=0;i<10<i++)
  {
    yield return new Example() {a=i};
  }
}
profile
There's Only One Thing To Do: Learn All We Can

0개의 댓글