Distinct() 메서드를 사용하여 C#의 목록에서 중복 항목을 제거합니다.
먼저 새 목록을 추가하십시오 -
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);
중복 요소를 제거하려면 아래와 같이 Distinct() 메서드를 사용하십시오 -
List<int> distinct = arr1.Distinct().ToList();
다음은 전체 코드입니다 -
예시
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("Initial List ...");
foreach (int i in arr1) {
Console.WriteLine(i);
}
// Removing duplicate elements
List<int> distinct = arr1.Distinct().ToList();
Console.WriteLine("List after removing duplicate elements ...");
foreach (int res in distinct) {
Console.WriteLine("{0}", res);
}
}
} 출력
Initial List ... 10 20 30 40 50 30 40 50 List after removing duplicate elements ... 10 20 30 40 50