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

C# 리스트에서 중복 요소 제거하기 – Distinct() 메서드 완벽 가이드

C#에서 리스트(List)에 같은 값이 여러 번 들어 있는 경우, LINQ의 Distinct() 메서드를 사용하면 간단하게 중복 요소를 제거할 수 있습니다. 이 메서드는 컬렉션에서 고유한 값만 남겨 반환해 주기 때문에 별도의 반복문이나 조건 처리 없이 한 줄로 해결됩니다.

1. 예제용 리스트 만들기

먼저 숫자가 중복되어 들어 있는 리스트를 하나 생성해 보겠습니다.

List<int> arr1 = new List<int>();
arr1.Add(10);
arr1.Add(20);
arr1.Add(30);
arr1.Add(40);
arr1.Add(50);
arr1.Add(30);
arr1.Add(40);
arr1.Add(50);

위 리스트에는 30, 40, 50이 각각 두 번씩 포함되어 있습니다.

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

중복을 제거하려면 Distinct()를 호출한 뒤, 결과를 다시 리스트로 변환하면 됩니다.

List<int> distinct = arr1.Distinct().ToList();

Distinct()는 IEnumerable 형식으로 결과를 반환하기 때문에, 원본과 동일한 List 타입으로 사용하려면 ToList()로 변환해 주는 것이 좋습니다.

3. 전체 예제 코드

아래는 리스트 생성부터 중복 제거, 결과 출력까지 전체 과정을 담은 완성 코드입니다.

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

public class Demo {
    public static void Main() {
        List<int> arr1 = new List<int>();
        arr1.Add(10);
        arr1.Add(20);
        arr1.Add(30);
        arr1.Add(40);
        arr1.Add(50);
        arr1.Add(30);
        arr1.Add(40);
        arr1.Add(50);

        Console.WriteLine("초기 리스트 ...");
        foreach (int i in arr1) {
            Console.WriteLine(i);
        }

        // 중복 요소 제거
        List<int> distinct = arr1.Distinct().ToList();

        Console.WriteLine("중복 제거 후 리스트 ...");
        foreach (int res in distinct) {
            Console.WriteLine("{0}", res);
        }
    }
}

4. 실행 결과

초기 리스트 ...
10
20
30
40
50
30
40
50
중복 제거 후 리스트 ...
10
20
30
40
50

정리

Distinct() 메서드는 기본적으로 요소의 기본 비교자(Default Comparer)를 사용하여 중복을 판별합니다. 숫자나 문자열처럼 단순한 타입에는 바로 적용할 수 있으며, 사용자 정의 클래스 객체의 중복을 제거하려면 IEqualityComparer<T>를 구현하거나 특정 속성을 기준으로 그룹화하는 방식을 함께 활용하면 됩니다. 또한 LINQ를 사용하므로 파일 상단에 using System.Linq; 네임스페이스를 반드시 추가해야 한다는 점도 기억하세요.