Computer >> 컴퓨터 >  >> 프로그래밍 >> C#

C# List에서 중복 요소를 손쉽게 제거하는 방법

C#에서 List<T>에 저장된 중복 요소를 제거하려면 LINQ에서 제공하는 Distinct() 메서드를 활용하면 됩니다. 별도의 반복문 없이 한 줄의 코드로 고유한 요소만 남긴 새로운 리스트를 만들 수 있습니다.

1. 리스트 선언 및 요소 추가

먼저 리스트를 선언하고 요소들을 추가합니다. 아래 예제에는 의도적으로 중복 값(50)을 포함시켰습니다.

List<int> list = new List<int>();
list.Add(50);
list.Add(90);
list.Add(50);
list.Add(100);

2. Distinct() 메서드로 중복 제거

Distinct() 메서드는 시퀀스에서 고유한 요소만 반환합니다. 여기에 ToList()를 호출하면 중복이 제거된 새로운 리스트를 얻을 수 있습니다.

List<int> myList = list.Distinct().ToList();

전체 예제 코드

다음은 리스트에서 중복 요소를 제거하는 전체 코드입니다.

using System;
using System.Collections.Generic;
using System.Linq;

public class Demo {
    public static void Main() {
        List<int> list = new List<int>();
        list.Add(50);
        list.Add(90);
        list.Add(50);
        list.Add(100);

        Console.WriteLine("Initial List...");
        foreach(int a in list) {
            Console.WriteLine("{0}", a);
        }

        List<int> myList = list.Distinct().ToList();
        Console.WriteLine("New List after removing duplicate elements...");
        foreach(int a in myList) {
            Console.WriteLine("{0}", a);
        }
    }
}

실행 결과

Initial List...
50
90
50
100
New List after removing duplicate elements...
50
90
100

정리

Distinct() 메서드는 기본적으로 요소의 기본 비교자(Default Comparer)를 사용해 중복 여부를 판단합니다. 숫자나 문자열처럼 단순한 타입에는 바로 적용할 수 있으며, 사용자 정의 객체의 경우 특정 속성 기준으로 중복을 제거하려면 추가 구현이 필요할 수 있습니다. 또한 원본 리스트는 그대로 유지되고, 결과는 새로운 리스트로 반환되므로 필요에 따라 원본을 대체하면 됩니다.