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()
{
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 :)