C# 中的 GroupBy() 方法
csharpprogrammingserver side programming更新于 2025/5/24 3:22:17
GroupBy() 是一种扩展方法,它根据某些键值从给定集合中返回一组元素。
以下是我们的数组 −
int[] arr = { 2, 30, 45, 60, 70 };
现在,我们将使用 GroupBy() 对小于 50 的元素进行分组 −
arr.GroupBy(b => chkSmaller(b));
上面的 chkSmaller() 查找小于 50 的元素。
让我们看看完整的代码 −
示例
using System;
using System.Linq;
class Demo {
static void Main() {
int[] arr = { 2, 30, 45, 60, 70 };
var check = arr.GroupBy(b => chkSmaller(b));
foreach (var val in check) {
Console.WriteLine(val.Key);
foreach (var res in val) {
Console.WriteLine(res);
}
}
}
static bool chkSmaller(int a) {
return a <= 50;
}
}
输出
True 2 30 45 False 60 70

