Array Count Examples
This page was last reviewed on Feb 1, 2024.
Dot Net Perls
Count elements. Think of a C# array. It has many elements—but how can we get this number? An array's elements can be counted in several ways.
Shows an array
Collections usually store their count in a field—this influences the performance of counting. There are some complexities with the syntax and speed of counting.
Arrays. For an array, we need to use Length (not Count). In programs, an array's size is set differently than List or ArrayList. The size does not grow dynamically.
Info 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.
Shows an array
using System; string[] roomItems = new string[3]; roomItems[0] = "cat"; roomItems[1] = "apple"; roomItems[2] = "frog"; // Count with Length property. Console.WriteLine(roomItems.Length);
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.
Tip This is identical to the List collection, which we will see next. This property access is fast.
using System; using System.Collections; ArrayList items = new ArrayList(); items.Add("One"); items.Add("Two"); // Count the elements in the ArrayList. int result = items.Count; Console.WriteLine(result);
List. Here we use List, a generic collection. We must specify its type in the angle brackets. These collections have superior performance and usually preferable.
Part 1 List has a property called Count that is fast to access. This property returns 2.
Part 2 This code shows Count() with parentheses. This is a LINQ extension method—it can be confusing if you don't know the difference.
using System; using System.Collections.Generic; using System.Linq; List<int> list = new List<int>(); list.Add(1); list.Add(2); // Part 1: count with the Count property. int result = list.Count; Console.WriteLine(result); // Part 2: count with the extension method. result = list.Count(); Console.WriteLine(result);
2 2
Count extension. You can use the Count() extension method when you have an IEnumerable collection or are using LINQ statements. But be careful with this method.
Tip Enumerations in C# are collections that haven't been determined exactly yet. They can use yield and foreach keywords.
using System; using System.Linq; string[] array = new string[] { "One", "Two", "Three" }; // An enumerable collection, not in memory yet. var e = from s in array select s; int c = e.Count(); // Extension method. Console.WriteLine(c); // Work is now done to get the count.
Benchmark, Count. Let us benchmark the Count() method. In my benchmark, where I took the Count of an array many times, the Count() extension performed worse.
Note The Count() method was iterating through the collection each time. This has poor algorithmic performance.
Version 1 This version uses the Count() extension method on the 100-element integer array.
Version 2 This version of the code tests the Length property on the array in the tight loop.
Result Version 2 (which access the Length property) performs much faster and is the preferable code.
using System; using System.Diagnostics; using System.Linq; const int _max = 1000000; var array = new int[100]; // Version 1: access Count() on array. var s1 = Stopwatch.StartNew(); for (int i = 0; i < _max; i++) { if (array.Count() != 100) { return; } } s1.Stop(); // Version 2: access Length on array. var s2 = Stopwatch.StartNew(); for (int i = 0; i < _max; i++) { if (array.Length != 100) { return; } } s2.Stop(); Console.WriteLine(((double)(s1.Elapsed.TotalMilliseconds * 1000000) / _max).ToString("0.00 ns")); Console.WriteLine(((double)(s2.Elapsed.TotalMilliseconds * 1000000) / _max).ToString("0.00 ns"));
32.49 ns Count() 0.79 ns Length
Hoist. In the C# language, the Length or Count property is often evaluated each time a for-loop is run. It can be faster 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.
using System; using System.Collections.Generic; var values = new List<int>() { 10, 20 }; // Loop over values, no hoisting. for (int i = 0; i < values.Count; i++) { Console.WriteLine($"VALUE: {values[i]}"); } // Loop over values, with hoisting of max. int max = values.Count; for (int i = 0; i < max; i++) { Console.WriteLine($"VALUE: {values[i]}"); }
Summary. We computed 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.
Dot Net Perls is a collection of tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.
This page was last updated on Feb 1, 2024 (edit).
© 2007-2024 Sam Allen.