Counting the number of elements in a sequence with LINQ C#

Say you have the following sequence of strings:

string[] bands = { "ACDC", "Queen", "Aerosmith", "Iron Maiden", "Megadeth", "Metallica", "Cream", "Oasis", "Abba", "Blur", "Chic", "Eurythmics", "Genesis", "INXS", "Midnight Oil", "Kent", "Madness", "Manic Street Preachers"
, "Noir Desir", "The Offspring", "Pink Floyd", "Rammstein", "Red Hot Chili Peppers", "Tears for Fears"
, "Deep Purple", "KISS"};

You can use the Count() extension method of IEnumerable to get the number of elements in the array:

Console.WriteLine(bands.Count());

…which returns 26. Count has an overload where you can specify a lambda filter. The following function returns the number of string elements which consist of at least 5 characters:

Console.WriteLine(bands.Count(s => s.Length >= 5));

…which returns 19.

IEnumerable has a LongCount method which has the same function and overloads as Count. It is used for collections whose size doesn’t fit into int.MaxValue and returns a long instead of an int. You can of course use it with small sequences as well but the returned value will be a long.

View the list of posts on LINQ here.

Elliot Balynn's Blog

A directory of wonderful thoughts

Software Engineering

Web development

Disparate Opinions

Various tidbits

chsakell's Blog

WEB APPLICATION DEVELOPMENT TUTORIALS WITH OPEN-SOURCE PROJECTS

Once Upon a Camayoc

Bite-size insight on Cyber Security for the not too technical.

%d bloggers like this: