使用linq的groupby方法结合range表达式或自定义键值,可以将数据按分数段分组并统计数量。具体做法是遍历集合,对每个元素计算其所属的区间(如0-59, 60-79, 80-100),然后按该区间键进行分组,最后调用count()获取每组的元素个数。

如何定义分数段的映射逻辑?
通过一个辅助函数或Lambda表达式将具体分数映射为字符串标签或整数区间ID,这是实现分段统计的关键步骤。例如,可以使用switch语句或if-else链来判断分数落在哪个区间,返回对应的键值。

using System;
using System.Linq;
using System.Collections.Generic;
public class ScoreStats
{
public static void Main()
{
var scores = new List<int> { 45, 72, 88, 55, 91, 30, 67, 82 };
var result = scores.GroupBy(s => GetScoreRange(s))
.Select(g => new { Range = g.Key, Count = g.Count() })
.OrderBy(x => x.Range)
.ToList();
foreach (var item in result)
{
Console.WriteLine($"{item.Range}: {item.Count}");
}
}
private static string GetScoreRange(int score)
{
if (score < 60) return "Fail (0-59)";
if (score < 80) return "Pass (60-79)";
return "Good (80+)";
}
}
预期输出结果如下: Fail (0-59): 3 Pass (60-79): 2 Good (80+): 3
如何处理空值或无效输入?
在统计前过滤掉null或负数等无效数据,确保GroupBy只处理有效记录。可以在查询开始时添加Where条件,排除不符合业务逻辑的分数值,避免产生异常或错误统计。

using System;
using System.Linq;
using System.Collections.Generic;
public class SafeScoreStats
{
public static void Main()
{
var scores = new List<int?> { 45, null, 72, 88, -5, 55, 91, 30, 67, 82 };
var result = scores.Where(s => s.HasValue && s.Value >= 0)
.Select(s => s.Value)
.GroupBy(s => GetScoreRange(s))
.Select(g => new { Range = g.Key, Count = g.Count() })
.ToList();
foreach (var item in result)
{
Console.WriteLine($"{item.Range}: {item.Count}");
}
}
private static string GetScoreRange(int score)
{
if (score < 60) return "Fail (0-59)";
if (score < 80) return "Pass (60-79)";
return "Good (80+)";
}
}
预期输出结果如下: Fail (0-59): 3 Pass (60-79): 2 Good (80+): 3
当分数正好等于边界值时归属哪个段?
边界值的归属取决于比较运算符的选择。在上述代码中,使用小于号(


















