LINQ Count Operator

By Indranil Chatterjee

Explains the usage of the Count operator from LINQ.

While some of the .NET collections (e.g. List<T>) provide a Count property, we don’t have it for all. This is where the Count operator from LINQ can be handy. As long as the collection implements IEnumerable<T>, we can use it. There is one overload that gives the count of all elements and another one lets us count all elements satisfying a condition.
Here is an example of both:

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

namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
  var persons = GetPersons();
  //This gets the total count
  Console.WriteLine("There are {0} persons in total", persons.Count());
  //This gets all persons with department as Engg
  Console.WriteLine("There are {0} engineers", persons.Count(p => p.Department.Equals("Engg")));
}

static IEnumerable<Person> GetPersons()
{
  return new List<Person>
{
    new Person { Name = "Indranil", Department = "Engg" },
    new Person { Name = "John", Department = "HR" },
    new Person { Name = "Shalini", Department = "Finance" },
    new Person { Name = "Steve", Department = "Engg" },
    new Person { Name = "George", Department = "Finance" },
  };
}
}

public class Person
{
    public string Name { get; set; }
    public string Department { get; set; }
}
}

If your data structure doesn’t implement IEnumerable<T> (e.g. ArrayList), you can use count as:
nonGenericSequence.OfType<Person>().Count();



LINQ Count Operator  (873 Views)