โ IComparable ์ธํฐํ์ด์ค
๊ฐ์ฒด์ ์ ๋ ฌ์ ์ ์ํ๋ ๋ฐ ์ฌ์ฉ๋๋ ์ธํฐํ์ด์ค๋ก ํด๋์ค๋ ๊ตฌ์กฐ์ฒด์ ์ธ์คํด์ค๋ฅผ ์๋ก ๋น๊ตํ ์ ์๊ฒ ํ์ฌ ์ ๋ ฌ, ๊ฒ์๋ฑ์ ์์ ์ด ๊ฐ๋ฅํ๊ฒ ํ๋ค.
๊ฐ์ฒด๋ฅผ ๋น๊ต ๊ฐ๋ฅํ๊ฒ ๋ง๋ค๊ธฐ ์ํด์ ์ธํฐํ์ด์ค์ CompareTo ๋ฉ์๋๋ฅผ ๊ตฌํํ์ฌ ๊ฐ์ฒด๊ฐ์ ์ ํ ๊ด๊ณ๋ฅผ ์ ์ํด์ผ ํ๋ค.
public interface IComparable<T>
{
int CompareTo(T other);
}
ex)
int IComparable<Person>.CompareTo(Person other)
{
return age - other.age;
}
CompareTo ๋ฉ์๋๋ ์ธ ๊ฐ์ง ๊ฐ์ ๋ฐํํ๋ค.
- ํ์ฌ ๊ฐ์ฒด๊ฐ ๋น๊ตํ ๋์๋ณด๋ค ์์ ๋ (๋น ๋ฅผ ๋) : ์์ (๋ณดํต -1)
- ํ์ฌ ๊ฐ์ฒด์ ๋น๊ตํ ๋์๊ณผ ๊ฐ์ ๋ : 0
- ํ์ฌ ๊ฐ์ฒด๊ฐ ๋น๊ตํ ๋์๋ณด๋ค ํด ๋ (๋๋ฆด ๋) : ์์ (๋ณดํต 1)
โ IComparer ์ธํฐํ์ด์ค
๋น๊ต ๋ก์ง์ ๋ณ๋์ ์ 3์ ๊ฐ์ฒด์๊ฒ ์ํ(์บก์ํ)ํ๋ ๊ฒ์ผ๋ก IComparable๋ณด๋ค ๋ฒ๊ฑฐ๋ก์ด ๋์ ํ์ฉ ๋ฒ์๊ฐ ๋๋ค.
๋น๊ต ๋ก์ง์ด ์ธ๋ถ์ ์ ์๋๋ฏ๋ก ๊ฐ์ ๊ฐ์ฒด์ ๋ํด ๋ค๋ฅธ ๋น๊ต์๋ฅผ ์ฌ์ฉํ์ฌ ์ ์ฐํ๊ฒ ๊ธฐ์ค์ ๋ณ๊ฒฝํ ์ ์๋ค.
public interface IComparer<T>
{
int Compare(T x, T y);
}
- x๊ฐ y๋ณด๋ค ์์ ๋ : ์์
- x์ y๊ฐ ๊ฐ์ ๋ : 0
- x๊ฐ y๋ณด๋ค ํด ๋ : ์์
ex)
public class AgeComparer : IComparer<Person>
{
public int Compare(Person x, Person y)
{
return x.age - y.age;
}
}
personList.Sort(new AgeComparer());
* ๊ธฐ์กด์ CompareTo ๋ฉ์๋๋ ๋ฌด์๋๊ธฐ ๋๋ฌธ์ CompareTo๊ฐ ์์ ์๊ฑฐ๋, ์์ ํ ์ ์์ ๋ ์ฌ์ฉ ๊ฐ๋ฅํ๋ค.
* ๊ฐ์ฒด ์ ๋ ฌ ์ IComparer๋ฅผ ์์๋ฐ์ ๊ฐ์ฒด ์์ฒด๋ฅผ ์ธ์๋ก ์ ๋ฌํด์ฃผ์ด์ผ ํ๋ค.
'๐ C#' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
| const, readonly (0) | 2024.08.19 |
|---|---|
| in, out, ref ํค์๋ (0) | 2024.08.19 |
| object ํ์ , ๋ฐ์ฑ, ์ธ๋ฐ์ฑ (0) | 2024.08.19 |
| ์ ๊ท ํํ์ (Regular Expression) (0) | 2024.08.14 |
| ํ์ฅ ๋ฉ์๋ (Extension Method) (0) | 2024.08.14 |