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.
Syntax:
Count<TSource>()
This method returns the total number of elements present in an array.
Count<TSource>(Func<TSource, Boolean>)
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.
C#
using System;
using System.Linq;
class GFG{
static public void Main()
{
var totalCount = 0;
string [] elements = { "Rem" , "Hisoka" , "Gon" ,
"Monkey D Luffy" , "Alvida" ,
"Shank" };
totalCount = elements.Count();
Console.WriteLine(totalCount);
}
}
|
Time Complexity : O(N) , here N is number of elements in string array.
Auxiliary Space : O(1), since no extra space used.
Example 2: Using integer values in the array.
C#
using System;
using System.Linq;
class GFG{
static public void Main()
{
var total = 0;
int [] nums = { 9, 6, 5, 2, 1, 5, 8, 4,
6, 2, 3, 4, 8, 7, 5, 6 };
total = nums.Count();
Console.WriteLine(total);
}
}
|
Time Complexity : O(N) , here N is number of elements in nums array.
Auxiliary Space : O(1), since no extra space used.
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.
C#
using System;
using System.Linq;
class GFG{
static public void Main()
{
var total = 0;
string [] colors = { "Red" , "Blue" , "Black" ,
"White" , "Blue" , "Blue" };
total = colors.Count(c => c == "Blue" );
Console.WriteLine(total);
}
}
|
Output:
3
Time Complexity : O(N) , here N is number of elements in string array.
Auxiliary Space : O(1), since no extra space used.
Last Updated :
23 Jan, 2023
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...