C# 程序从序列中获取不同元素

csharpprogrammingserver side programming更新于 2025/9/14 21:19:00

设置序列并添加元素。

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 };
      // 获取不同元素
      IEnumerable<int> res = ID.AsQueryable().Distinct();
      foreach (int arr in res) {
         Console.WriteLine(arr);
      }
   }
}

输出

120
111
250
300
399
450

相关文章