Using C# LINQ - A Practical Overview

player_one
5,491 views

Open Source Your Knowledge, Become a Contributor

Technology knowledge has to be shared and made accessible for free. Join the movement.

Create Content

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 to IEnumerable<T>) is slightly different from the Count property on List<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 a long, 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.

Count Exercise
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
using System.Collections.Generic;
using System.Linq;
namespace SingleCalculatedValue1
{
public static class Count1
{
// Return the number of strings in the provided sequence that begin with
// the provided startString.
public static int NumberThatStartWith(IEnumerable<string> words, string startString)
{
// Uncomment:
// return words.???();
}
}
}
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
Open Source Your Knowledge: become a Contributor and help others learn. Create New Content