用 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

更新於: 22-06-2020

538 次檢視

啟動您的 事業

完成課程以獲得認證

開始
廣告
© . All rights reserved.