Get count of number of items in a List in C#
This post will discuss how to get the count of the number of items in a list in C#.
The Count property returns the number of elements contained in the List. This works in O(1) time and can be used as follows:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
using System; using System.Collections.Generic; public class Example { public static void Main() { List<int> values = new List<int> { 1, 2, 3, 4, 5 }; int size = values.Count; Console.WriteLine("The count of list is {0}", size); } } |
Output:
The number of elements in the list is 5
In LINQ, you can use the Count() extension method to obtain the count of elements, as the following example illustrates. Note that it might translate to an invocation of List’s Count property.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
using System; using System.Linq; using System.Collections.Generic; public class Example { public static void Main() { List<int> values = Enumerable.Repeat(0, 5).ToList(); int size = values.Count(); Console.WriteLine("The number of elements in the list is {0}", size); } } |
Output:
The number of elements in the list is 5
Alternatively, to get the count of a single element, filter the list using the Where() method to obtain matching values with the specified target, and then get its count by invoking the Count() method.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
using System; using System.Linq; using System.Collections.Generic; public class Example { public static void Main() { List<int> values = new List<int> { 2, 5, 1, 1, 2, 2, 4 }; int target = 2; int count = values.Where(x => x.Equals(target)).Count(); Console.WriteLine("Element {0} occurs {1} times", target, count); } } |
Output:
Element 2 occurs 3 times
That’s all about getting the count of the number of items in a list in C#.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)