ADVERTISEMENT
ADVERTISEMENT

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 »


ADVERTISEMENT



ADVERTISEMENT



Comments and Discussions


ADVERTISEMENT

ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT

Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.