Search code examples
c#listcountcontainspercentage

How to check if at least n% of a list contains certain value x?


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*/
}

Solution

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