CSharp - LINQ Count

Introduction

The Count operator returns the number of elements in the input sequence.

Prototypes

There are two prototypes we cover. The First CountPrototype

public static int Count<T>(
    this IEnumerable<T> source);

This prototype of the Count operator returns the total number of elements in the source input sequence.

If the input implements the ICollection<T> interface, it obtains the count using the implementation of that interface.

If the source input sequence does not implement the ICollection<T> interface, it enumerates the entire input sequence counting the number of elements.

The second prototype of the Count operator enumerates the source input sequence and counts every element by the predicate.

public static int Count<T>(
        this IEnumerable<T> source,
        Func<T, bool> predicate);

Exceptions

ArgumentNullException is thrown if any argument is null.

OverflowException is thrown if the count exceeds the capacity of int.MaxValue.

Demo

using System;
using System.Linq;
using System.Collections;
using System.Collections.Generic;
class Program//from   w ww . j  a  va2  s. com
{
    static void Main(string[] args)
    {        
        string[] codeNames = {"Python", "Java", "Javascript", "Bash", "C++", "Oracle"};
        int count = codeNames.Count();
        Console.WriteLine(count);
    }
}

Result

Related Topics