1

Is there any existing simple method in C# where I can check if a list contains at least n% of a certain value.

Something like this pseudocode:

if ( myList.Contains(5).percentage(75) )
{
  /*do something*/
}
JohnDoe
  • 825
  • 1
  • 13
  • 31

1 Answers1

3

If you are asking to count the items with a value of 5 and this amount exceeds 75% of the number of items in the list:

if ( myList.Where(value => value == 5).Count() >= myList.Count * 75 / 100 )
{
}

Or also:

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 )
{
}

The use of Round makes it possible to refine the test condition according to the percentage.

Enumerable.Count Method

Percentage calculation


As suggested by @cmos we can create an extension medthod to refactor that:

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;
  }
}

Usage

if ( myList.IsCountReached(5, 75) )
{
}

From the long awaited 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;
  }
}
  • this would be expensive because it needs to iterate through all elements, even though you can early break out if the result is satisfied – phuclv Aug 20 '21 at 07:50
  • @phuclv Indeed, the use of a handmade loop and a break will be more optimized, but Count is the closest available .NET API to what the OP requests. –  Aug 20 '21 at 08:01