Home »
.Net »
C# Programs
C# program to demonstrate the use of the method as a condition in the Linq where() method of List collection
Here, we are going to learn the use of the method as a condition in the Linq where() method of List collection in C#.
Submitted by Nidhi, on August 28, 2020
Here we will find the even numbers using Linq where() method of list collection. Here we pass a method as a parameter inside where() method that will return a boolean value.
Program:
The source code to demonstrate the use of the method as a condition in the Linq Where method, is given below. The given program is compiled and executed successfully on Microsoft Visual Studio.
//C# Program to demonstrate the use of the method
//as a condition in Linq Where the method of List collection.
using System;
using System.Collections.Generic;
using System.Linq;
class Demo
{
static bool checkEven(int num)
{
if (num % 2 == 0)
return true;
else
return false;
}
static void Main(string[] args)
{
List<int> intnums = new List<int>();
intnums.Add(10);
intnums.Add(11);
intnums.Add(12);
intnums.Add(13);
intnums.Add(14);
IEnumerable<int> result = intnums.Where(num => checkEven(num));
Console.WriteLine("Even Numbers:");
foreach (int even in result)
{
Console.WriteLine(even);
}
}
}
Output:
Even Numbers:
10
12
14
Press any key to continue . . .
Explanation:
In the above program, we created a list that contains integer numbers. Here we defined a static method to check the specified number is even or not.
IEnumerable<int> result = intnums.Where(num => checkEven(num));
Here we passed checkEven() method inside the where() method and filter even numbers.
Console.WriteLine("Even Numbers:");
foreach (int even in result)
{
Console.WriteLine(even);
}
Here we printed filtered even numbers on the console screen.
C# LINQ Programs »