Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / Languages / C#

Count number of occurences of a value in a List using LINQ

2.33/5 (3 votes)
29 Mar 2010CPOL 1  
Did you ever face a situation where you want to calculate total number of occurrences of a value in a List object?What approach did you used for it?Did you ever try LINQ for the same? Yes, you can use it. Just look at the example below:class Program{ static void Main() ...
Did you ever face a situation where you want to calculate total number of occurrences of a value in a List object?

What approach did you used for it?

Did you ever try LINQ for the same? Yes, you can use it. Just look at the example below:

C#
class Program
{
    static void Main()
    {
        List<int> list = new List<int>();
        list.AddRange(new int[] { 1, 2, 3, 2, 1, 4, 5, 1, 7, 1, 8, 1});
        Console.WriteLine("1 occurs {0} times.", CountOccurenceOfValue(list, 1));
        Console.WriteLine("1 occurs {0} times.", CountOccurenceOfValue2(list, 1));
    }

    static int CountOccurenceOfValue(List<int> list, int valueToFind)
    {
        return ((from temp in list where temp.Equals(valueToFind) select temp).Count());
    }

    static int CountOccurenceOfValue2(List<int> list, int valueToFind)
    {
        int count = list.Where(temp => temp.Equals(valueToFind))
                    .Select(temp => temp)
                    .Count();
        return count;
    }
}



Hope this will help :)

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)