This is my new post in extension to previous one of finding count of a item in ArrayList using LINQ which can be found here , in this post we will see how to get count of particular item in a List using LINQ.
The method to get count:
public int GetCountInList<T>(IEnumerable<T> list, T key)
{
int iCount = 0;
iCount=list.Count(item => EqualityComparer<T>.Default.Equals(item, key));
return iCount;
}
Use of the method :
List<int> lstNos = new List<int>();
lstNos.Add(1);
lstNos.Add(2);
lstNos.Add(1);
lstNos.Add(3);
lstNos.Add(2);
lstNos.Add(2);
int i = 0;
i=GetCountInList<int>(lstNos, 1);
Console.WriteLine("Count of 1 is = " + i);
List<string> lstNames = new List<string>();
lstNames.Add("Jhon");
lstNames.Add("Jhon");
lstNames.Add("Bob");
lstNames.Add("Mike");
lstNames.Add("Jhon");
lstNames.Add("Mike");
i = GetCountInList<string>(lstNames, "Jhon");
Console.WriteLine();
Console.WriteLine("Count of Jhon is = " + i);
Console.ReadLine();
List<int> lstNos = new List<int>();
lstNos.Add(1);
lstNos.Add(2);
lstNos.Add(1);
lstNos.Add(3);
lstNos.Add(2);
lstNos.Add(2);
int i = 0;
i=GetCountInList<int>(lstNos, 1);
Console.WriteLine("Count of 1 is = " + i);
List<string> lstNames = new List<string>();
lstNames.Add("John");
lstNames.Add("John");
lstNames.Add("Bob");
lstNames.Add("Mike");
lstNames.Add("John");
lstNames.Add("Mike");
i = GetCountInList<string>(lstNames, "John");
Console.WriteLine();
Console.WriteLine("Count of Jhon is = " + i);
Console.ReadLine();
Output :
Count of 1 is = 2
Count of John is = 3
Note:
The above method works with almost all traditional data types.
Deven Sawant