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


Exercises in .NET with Andras Nemes

Say you have the following sequence of strings:

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:

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

View original post

Advertisements

Leave a Reply

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

WordPress.com Logo

You are commenting using your WordPress.com 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 )

Google+ photo

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

Connecting to %s