【问题标题】:How to check if at least n% of a list contains certain value x?如何检查列表的至少 n% 是否包含某个值 x?
【发布时间】:2021-10-21 18:35:04
【问题描述】:

在 C# 中是否有任何现有的简单方法可以检查列表是否包含至少 n% 的某个值。

类似这样的伪代码:

if ( myList.Contains(5).percentage(75) )
{
  /*do something*/
}

【问题讨论】:

  • 据我所知,没有内置方法。我会使用 LINQ Count 方法并自己计算百分比。
  • 我认为你已经大大高估了这种检查的普遍性,期望有一个框架方法。
  • 如果你想使用类似LINQ的语法,我建议你为你的用例编写自己的扩展方法

标签: c# list count contains percentage


【解决方案1】:

如果您要求对值为 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;
  }
}

【讨论】:

  • 这会很昂贵,因为它需要遍历所有元素,即使如果结果满意你可以提前突破
  • @phuclv 确实,使用手工循环和中断会更加优化,但 Count 是最接近 OP 请求的可用 .NET API。
猜你喜欢
  • 2022-01-22
  • 2015-07-23
  • 1970-01-01
  • 1970-01-01
  • 2017-10-16
  • 2014-05-26
  • 1970-01-01
  • 1970-01-01
  • 2018-03-21
相关资源
最近更新 更多