목록을 선언하고 요소를 추가합니다.
List<int> list = new List<int>(); list.Add(50); list.Add(90); list.Add(50); list.Add(100);
이제 Distinct() 메서드를 사용하여 고유한 요소만 가져옵니다.
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