C#如何判断列表中特定值x的占比是否达到至少n%?
C# 原生没有直接匹配你期望写法的内置API,但可以通过编写可复用的泛型扩展方法,实现和你示例逻辑完全一致的调用体验,实现成本极低。
实现代码
你只需要新增一个静态扩展类,针对IEnumerable<T>编写通用校验方法即可:
public static class CollectionExtension { /// <summary> /// 校验集合中指定值的占比是否不低于最低阈值 /// </summary> /// <param name="source">目标集合</param> /// <param name="target">要校验的指定值</param> /// <param name="minPercentage">最低占比阈值(单位%)</param> public static bool MeetPercentageThreshold<T>(this IEnumerable<T> source, T target, double minPercentage) { // 空集合直接返回false避免除以0异常 if (source == null || !source.Any()) return false; int total = source.Count(); int matchCount = source.Count(x => EqualityComparer<T>.Default.Equals(x, target)); return (matchCount * 100.0 / total) >= minPercentage; } }
调用效果
扩展方法编写完成后,你就可以用非常简洁的方式调用,完全贴合你的预期逻辑:
if (myList.MeetPercentageThreshold(5, 75)) { /* 执行对应业务逻辑 */ }
优化说明
如果你需要处理超大规模集合,不想遍历两次集合统计数量,可以调整实现为单次遍历版本,性能更高:
public static bool MeetPercentageThreshold<T>(this IEnumerable<T> source, T target, double minPercentage) { if (source == null) return false; int total = 0; int matchCount = 0; foreach (var item in source) { total++; if (EqualityComparer<T>.Default.Equals(item, target)) { matchCount++; } } return total == 0 ? false : (matchCount * 100.0 / total) >= minPercentage; }
该方法支持所有实现了IEnumerable<T>的集合类型,包括List、数组、Queue、HashSet等,无需针对不同集合类型单独适配。
内容的提问来源于stack exchange,提问作者JohnDoe
相关产品推荐
相关产品推荐

