How to Count Elements in C# Array?
To count the number of elements in the C# array, we can use the count() method from the IEnumerable. It is included in the System.Linq.Enumerable class. The count method can be used with any type of collection such as an array, ArrayList, List, Dictionary, etc.
This method returns the total number of elements present in an array.
This method returns the total number of elements in an array that matches the specified condition using Func delegate.
Example 1: Using String values in the array.
In the below code block, we have implemented the count function to count the number of elements in a C# Array. Firstly, we have used the System.Linq, because the count function is located in this class, then we have created a count variable to count the number of elements in the array. After that, we have created an array of strings with 6 elements in it. Then we have used the Count function in the array and store the resultant count into the count variable that we have created earlier. Then using the console. Write line we are displaying the count of elements in the array.
Example 2: Using integer values in the array.
Example 3: To count specific elements based on conditions within the array.
Here, in the below program, we are creating an array of colors, and then using the count method, we are finding the number of times the color “Blue” appears in the array. Then displaying the count.