C# - Method as a condition in LINQ where() method of List collection

Learn, how to use the method as a condition in the Linq where() method of List collection in C#? By Nidhi Last updated : April 01, 2023

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.

C# program to demonstrate the use of the method as a condition in the LINQ where() method of List collection

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 »




Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.