Sử dụng phương thức Distinction () để xóa các bản sao khỏi danh sách trong C #.
Đầu tiên, hãy thêm một danh sách mới -
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);
Để loại bỏ các phần tử trùng lặp, hãy sử dụng phương thức Distinction () như được hiển thị bên dưới -
List<int> distinct = arr1.Distinct().ToList();
Đây là mã hoàn chỉnh -
Ví dụ
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);
}
}
} Đầu ra
Initial List ... 10 20 30 40 50 30 40 50 List after removing duplicate elements ... 10 20 30 40 50