从序列中获取唯一元素的 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.