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:


…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.

About Andras Nemes
I'm a .NET/Java developer living and working in Stockholm, Sweden.

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

  1. Tharaka says:

    Its an awesome tutorial.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

Elliot Balynn's Blog

A directory of wonderful thoughts

Software Engineering

Web development

Disparate Opinions

Various tidbits

chsakell's Blog


Once Upon a Camayoc

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

%d bloggers like this: