C#에서 리스트를 정렬하는 방법에는 List<T>.Sort()라는 기본 매서드가 존재한다.
해당 매서드는 크기비교가 가능한 형식이 리스트에 들어가 있을 경우에만 사용이 가능하다.
List<T> 내의 클래스 안에 들어있는 데이터를 이용해서 정렬하는 방법이 필요할 경우에 사용할 수 있는 방법은 아래에 있는 코드를 통해서 사용 가능하다.
아래의 코드는 RandomPoints라는 Point 클래스의 리스트를 Point 안의 Distance값의 오름차순으로 정렬한 예시이다.
if 문 안의 부호를 반대로 변경하면 Distance 값의 내림차순으로 정렬을 할 수 있다.
using System;
using System.Collections.Generic;
List<Point> RandomPoints;
public class Point
{
public double Distance { get; set;}
public Point DeepCopy()
{
Point info = new Point();
info.Distance = Distance;
}
}
for (int i = 0; i < RandomPoints.Count - 1; i++)
{
for (int j = i + 1; j < RandomPoints.Count; j++)
{
if (RandomPoints[i].Distance < RandomPoints[j].Distance)
{
Point Temp = RandomPoints[i].DeepCopy();
RandomPoints[i] = RandomPoints[j].DeepCopy();
RandomPoints[j] = Temp.DeepCopy();
}
}
}
'C#' 카테고리의 다른 글
[C#] 파일을 줄단위로 마지막까지 읽어오기 (0) | 2023.04.19 |
---|
댓글