Count the Number of Element Present in the Sequence in LINQ?


Language Integrated Query (LINQ) is a powerful feature in C# that allows for efficient data manipulation. One common task when working with collections is determining the number of elements in a sequence. This article will guide you through using LINQ to count the number of elements in a sequence, a fundamental operation for data analysis and manipulation.

Understanding LINQ and Sequences

LINQ is a set of technologies based on the integration of query capabilities directly into the C# language. With LINQ, you can query data from a variety of sources, including arrays, enumerable classes, XML documents, relational databases, and third-party data sources.

A sequence, in the context of LINQ, is any object that implements the IEnumerable interface or the generic IEnumerable interface.

Using the Count Method in LINQ

LINQ provides the Count method, which returns the number of elements in a sequence.

Example

Here's a simple example of how to use the Count method −

using System;
using System.Collections.Generic;

class Program {
   static void Main(){
      List<int> numbers = new List<int> { 1, 2, 3, 4, 5 };

      int count = numbers.Count;

      Console.WriteLine(count);  // Outputs: 5
   }
}

Output

5

Counting Elements That Satisfy a Condition

You can also use the Count method with a predicate — a function that returns true or false. This allows you to count only the elements that satisfy a certain condition.

Example

using System;
using System.Collections.Generic;
using System.Linq;

class Program {
   static void Main() {
      List<int> numbers = new List<int> { 1, 2, 3, 4, 5 };

      int evenCount = numbers.Count(n => n % 2 == 0);

      Console.WriteLine(evenCount);  // Outputs: 2
   }
}

In this example, the Count method counts only the elements in numbers that are even. The predicate n => n % 2 == 0 is true for even numbers and false for odd numbers.

Output

2

Conclusion

Counting the number of elements in a sequence is a fundamental operation in data manipulation and analysis. With LINQ in C#, you can not only count the total number of elements in a sequence but also count the elements that satisfy a specific condition. This feature adds to the versatility and expressiveness of C# as a language for data processing and manipulation.

Updated on: 24-Jul-2023

167 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements