C#:Array

.NET Array Dictionary List String 2D Async DataTable Dates DateTime Enum File For Foreach Format IEnumerable If IndexOf Lambda Parse Path Process Property Regex Replace Row Sort Split Static StringBuilder Substring Switch Tuple Window

Count Array Elements. An array's elements can be counted in several ways. Collections in the C# programming language store their count in a field. This influences the performance of counting. There are some complexities with the syntax and speed of counting.
Counting guidelines:

For ArrayList, List:   Use Count property.
For array:             Use Length property.
For IEnumerable:       Use Count() method.
ArrayList. Here we get the number of elements in an ArrayList, which is a non-generic collection that stores its length in a property called Count. This is identical to the List collection, which we will see next. This property access is fast.ArrayList
C# program that uses ArrayList

using System;
using System.Collections;

class Program
{
    static void Main()
    {
	ArrayList ar = new ArrayList();
	ar.Add("One");
	ar.Add("Two");

	// Count the elements in the ArrayList.
	int c = ar.Count;
	Console.WriteLine(c);
    }
}

Output

2
List. Here we use List, a generic collection. You must specify its type in the sharp angle brackets <T>. These collections have superior performance and usually preferable. List has a property called Count that is fast to access.Property
C# program that uses List

using System;
using System.Collections.Generic;
using System.Linq;

class Program
{
    static void Main()
    {
	List<int> list = new List<int>();
	list.Add(1);
	list.Add(2);

	// Count with the Count property.
	int c = list.Count;
	Console.WriteLine(c);

	// Count with the extension method. This is different!
	c = list.Count(); // BE CAREFUL!
	Console.WriteLine(c);
    }
}

Output

2
2
Please look at the two int assignments. The list.Count accesses a property and is fast. It will return 2. The code shows Count() with parentheses. This is a LINQ extension method—it can be confusing if you don't know the difference.

Tip: This is a method that works on IEnumerables. It loops through the elements to count.

IEnumerable
Arrays. Arrays are counted differently and you need to use Length. In programs, an array's size is set differently than List or ArrayList, and it does not grow dynamically. The Length value will include all elements.Array Length Property

Last element: We use the Length property on arrays, and also the Count property on ArrayList and List, to access the final element.

Tip: The final element is located at the count minus one, except when the length of the array is 0.


Count extension. You can use the Count() extension method when you have an IEnumerable collection or are using LINQ statements. Enumerations in C# are collections that haven't been determined exactly yet, and they can use yield and foreach keywords.
C# program that uses LINQ

using System;
using System.Linq;

class Program
{
    static void Main()
    {
	string[] arr = new string[]
	{
	    "One",
	    "Two",
	    "Three"
	};

	// An enumerable collection, not in memory yet.
	var e = from s in arr
		select s;

	int c = e.Count(); // Extension method.
	Console.WriteLine(c);
	// ... does a lot of work to get the count.
    }
}

Output

3
Benchmark. The Count extension method is a lot slower. In my benchmark, where I took the Count of an array 10,000 times, the Count() extension performed several times slower. It was likely iterating through the collection each time.Benchmark
Count extension method performance:
    (10,000 iterations of 10,000 iterations)

Count property:  452 ms
Count() method: 2623 ms
Hoist. In the C# language, the Length or Count property is often evaluated each time a for-loop is run. Because of this, it can be advantageous to hoist the Count or Length check out of the loop.

Note: Occasionally the JIT compiler can optimize loops that include the Count or Length in the for statement.

Note 2: Hoisting is sometimes faster. For optimal performance, you will need to test your program. Not hoisting can be faster.

Count variable hoisted

int a = list.Count;
for (int i = 0; i < a; i++)
{
}

Not hoisted

for (int i = 0; i < list.Count; i++)
{
}
Summary. We saw several ways to get the element count of a List or array. And we saw some benchmarks of the extension method that also is named Count. You will need to use Count in most for-loops. Hoisting it is not always beneficial.

So: The Count and Length properties are computed automatically and are fast. Avoid the Count() extension method when possible.

Count Extension Method