基于谓词过滤数组元素的 C# 程序

programmingserver side programmingcsharp更新于 2025/9/15 22:30:00

设置一个数组。

int[] arr = { 40, 42, 12, 83, 75, 40, 95 };

使用 Where 子句和谓词获取 50 以上的元素。

IEnumerable<int> myQuery = arr.AsQueryable() .Where((a, index) => a >= 50);

让我们看看完整的代码 −

示例

using System;
using System.Linq;
using System.Collections.Generic;

public class Demo {
   public static void Main() {
      int[] arr = { 40, 42, 12, 83, 75, 40, 95 };
      Console.WriteLine("Array:");
      foreach (int a in arr) {
         Console.WriteLine(a);
      }
      // 获取 70 以上的元素
      IEnumerable<int> myQuery = arr.AsQueryable() .Where((a, index) => a >= 50);
      Console.WriteLine("Elements above 50...:");
      foreach (int res in myQuery) {
         Console.WriteLine(res);
      }
   }
}

输出

Array:
40
42
12
83
75
40
95
Elements above 50...:
83
75
95

相关文章