Using C# LINQ - A Practical Overview
Open Source Your Knowledge, Become a Contributor
Technology knowledge has to be shared and made accessible for free. Join the movement.
Methods - Calculating a single value
The LINQ methods in this chapter examine the elements of an IEnumerable<T>
sequence and return a result based on the examined values. For most of the methods we will discuss, this returned result will be either a bool
or an int
.
Count() method
In its simplest form (without any parameters), the Count()
method returns an int
indicating the number of elements in the source sequence.
IEnumerable<string> strings = new List<string> { "first", "then", "and then", "finally" };
// Will return 4
int result = strings.Count();
NOTE: The
Count()
LINQ method (an extension method toIEnumerable<T>
) is slightly different from theCount
property onList<T>
. This unfortunate situation can cause some confusion. More on this in the Advanced Topics course.
NOTE: There is also a
LongCount()
method that returns along
, for use with sequences that have a large number of elements.
Count(<predicate>) method
There is another form of the Count()
method that takes a predicate delegate parameter. The provided delegate should take a parameter of type T
and return a bool
indicating whether or not the provided parameter meets the criteria.
This form of Count()
will return an int
indicating the number of elements in the source sequence that meet the criteria. This produces the same result as <source>.Where(<condition>).Count()
.
IEnumerable<string> strings = new List<string> { "first", "then", "and then", "finally" };
// Will return 2
int result = strings.Count(str => str.Contains("then"));
Count() exercise
In the following exercise, count the number of strings in the provided sequence that begin with the provided string.
HINT: Use the
String.StartsWith()
method.