用 C# 程式移除 List 中的重複元素
宣告一個列表並新增元素。
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();
以下是從 List 中刪除重複元素的完整程式碼 −
示例
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
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP