如何检查列表的至少 n% 是否包含特定值 x?
How to check if at least n% of a list contains certain value x?
C# 中是否存在任何现有的简单方法,我可以在其中检查列表是否至少包含特定值的 n%。
类似这样的伪代码:
if ( myList.Contains(5).percentage(75) )
{
/*do something*/
}
如果您要计算值为 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的使用使得根据百分比细化测试条件成为可能。
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;
}
}
C# 中是否存在任何现有的简单方法,我可以在其中检查列表是否至少包含特定值的 n%。
类似这样的伪代码:
if ( myList.Contains(5).percentage(75) )
{
/*do something*/
}
如果您要计算值为 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的使用使得根据百分比细化测试条件成为可能。
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;
}
}