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 in C#

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

LINQ Count() Function Syntax in 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 the LINQ Count() function.

 

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

LINQ Count() Function Example in 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 in 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 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.