如果您要求对值为 5 的项目进行计数,并且该数量超过列表中项目数量的 75%:
if ( myList.Where(value => value == 5).Count() >= myList.Count * 75 / 100 )
{
}
也可以:
using System;
using System.Linq;
var myList = new List<int>();
int valueToCheck = 5;
double percentTrigger = 0.75;
int countTrigger = (int)Math.Round(myList.Count * percentTrigger);
if ( myList.Count(value => value == valueToCheck) >= countTrigger )
{
}
使用 Round 可以根据百分比细化测试条件。
Enumerable.Count Method
Percentage calculation
正如@cmos 所建议的,我们可以创建一个扩展方法来重构它:
static public class EnumerableHelper
{
static public bool IsCountReached(this IEnumerable<int> collection, int value, int percent)
{
int countTrigger = (int)Math.Round((double)collection.Count() * percent / 100);
return collection.Count(item => item == value) >= countTrigger;
}
}
用法
if ( myList.IsCountReached(5, 75) )
{
}
来自期待已久的Preview Features in .NET 6 – Generic Math:
static public class EnumerableHelper
{
static public bool IsCountReached<T>(this IEnumerable<T> collection, T value, int percent)
where T : INumber<T>
{
int countTrigger = (int)Math.Round((double)collection.Count() * percent / 100);
return collection.Count(item => item == value) >= countTrigger;
}
}