LINQ Count Function to Count Items in List

Total Views : 1885
Keywords : How to use count() function to count number of items / elements in list with example, Linq query to count number of items in list with example

Here we will learn linq count() function / operator in c#, vb.net with example and how to use linq count() function / operator to count number items / elements in list or collection object in c#, vb.net with examples.

LINQ Count() Function

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

Syntax of LINQ Count() Function

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

C# Code

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

int Count = Num.Count();

VB.NET Code

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

Dim Count As Integer = Num.Count()

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

LINQ Count() Function Example

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

C# Code

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);

}

}

}

VB.NET Code

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)

End Sub

End Module

Here we used Count() function to find out the count from a given collection “Num”. Now we will run and see the output that would be like as shown below

Output of LINQ Count() Function

Following is the result of using LINQ Count() function to count number of items in array list.

Find the count of the elements:

The Count is 9

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