LINQ Count Function to Count Items in List

In LINQ, Count() function is useful to count the number of elements in the list or collection.

 

Following is the syntax of defining the LINQ count function to count the number of items in the list.

Syntax of LINQ Count() Function C#

int[] Num = { 1, 2, 3, 4, 5, 6, 7, 8, 9 };

int Count = Num.Count();

LINQ Count() Function Syntax VB.NET

Dim Num As Integer() = {1, 2, 3, 4, 5, 6, 7, 8, 9}

Dim Count As Integer = Num.Count()

If you observe the above syntax, we are counting the number of items in the "Num" list using linq Count() function.

 

Now, we will see the example of using linq Count() function to count the number of items in the collection / list.

LINQ Count() Function Example C#

using System;

using System.Collections.Generic;

using System.Linq;

 

namespace Linqtutorials

{

class Program

{

static void Main(string[] args)

{

int[] Num = { 1, 2, 3, 4, 5, 6, 7, 8, 9 };

Console.WriteLine("Find the count of the elements:");

int Count = Num.Count();

Console.WriteLine("The Count is {0}", Count);

Console.ReadLine();

}

}

}

LINQ Count() Function Example VB.NET

ModuleModule1

Sub Main()

Dim Num As Integer() = {1, 2, 3, 4, 5, 6, 7, 8, 9}

Console.WriteLine("Find the count of the elements:")

Dim Count As Integer = Num.Count()

Console.WriteLine("The Count is {0}", Count)

Console.ReadLine()

End Sub

End Module

Here, we used Count() function to find out the count of a given collection “Num”.

 

When we execute the above LINQ Count() examples, we will get the result like as shown below.

 

Find the count of the elements:

 

The Count is 9

This is how we can use the LINQ count() function to count the number of items in the list or collection object.

Topics Covered