從序列中獲取唯一元素的 C# 程式


設定序列並新增元素。

List<int> ID = new List<int> { 120, 111, 250, 111, 120, 300, 399, 450 };

使用 Distinct() 方法從上述列表中獲取唯一元素。

IEnumerable<int> res = ID.AsQueryable().Distinct();

我們看一下完整程式碼。

示例

 線上演示

using System;
using System.Linq;
using System.Collections.Generic;
class Demo {
   static void Main() {
      List<int> ID = new List<int> { 120, 111, 250, 111, 120, 300, 399, 450 };
      // get distinct elements
      IEnumerable<int> res = ID.AsQueryable().Distinct();
      foreach (int arr in res) {
         Console.WriteLine(arr);
      }
   }
}

輸出

120
111
250
300
399
450

更新日期:2020 年 6 月 23 日

249 次瀏覽

開啟你的 職業生涯

完成課程獲得認證

開始學習
廣告
© . All rights reserved.