How to count specific elements in the array in C#?
You can count the total number of elements or some specific elements in the array using an extension method Count() method.
The Count()
method is an extension method of IEnumerable included in System.Linq.Enumerable
class. It can be used with any collection or a custom class that implements IEnumerable
interface. All the built-in collections in C#, such as array, ArrayList, List, Dictionary, SortedList, etc. implements IEnumerable, and so the Count()
method can be used with these collection types.
Count() Overloads
Count<TSource>() | Returns total number of elements in an array. |
Count<TSource>(Func<TSource, Boolean>) | Returns the total number of elements in an array that matches the specified condition using Func delegate. |
The following example displays the total number of elements in the array.
string[] empty = new string[5];
var totalElements = empty.Count(); //5
string[] animals = { "Cat", "Alligator", "fox", "donkey", "Cat", "alligator" };
totalElements = animals.Count(); //6
int[] nums = { 1, 2, 3, 4, 3, 55, 23, 2, 5, 6, 2, 2 };
totalElements = nums.Count(); //12
In the above example, the empty.Count() returns 5, even if there are no elements in the array. This is because an array already has five null elements. For others, it will return the total number of elements.
Count Specific Elements in an Array
The following example shows how to count the specific elements based on some condition.
string[] animals = { "Cat", "Alligator", "fox", "donkey", "Cat", "alligator" };
var totalCats = animals.Count(s => s == "Cat");
var animalsStartsWithA = animals1.Count(s => s.StartsWith("a", StringComparison.CurrentCultureIgnoreCase));
int[] nums = { 1, 2, 3, 4, 3, 55, 23, 2, 5, 6, 2, 2 };
var totalEvenNums = nums.Count(n => n%2==0);
You can also use Regex with the Count()
method, as shown below.
string[] animals = { "Cat", "Alligator", "fox", "donkey", "Cat", "alligator" };
var animalsWithCapitalLetter = animals.Count(s =>
{
return Regex.IsMatch(s, "^[A-Z]");
});