C# program to generate random even numbers using LINQ parallel query

Here, we are going to learn how to generate random even numbers using LINQ parallel query in C#?
Submitted by Nidhi, on August 20, 2020

In this program, we will generate random even numbers using LINQ parallel query, here we will put a condition to check the number is even or not in the specified range. Here we used range 1 to 50.

Program:

The source code to generate random even numbers using LINQ parallel query in C# is given below. The given program is compiled and executed successfully on Microsoft Visual Studio.

//Program to generate random even numbers 
//using LINQ parallel query.

using System;
using System.Collections.Generic;
using System.Linq;

class RandomEvens
{
    static void Main(string[] args)
    {
        IEnumerable<int> Numbers = ((ParallelQuery<int>)ParallelEnumerable.Range(1,50))
        .Where(num => num % 2 == 0)
        .Select(val => val);

        foreach (int evens in Numbers) 
        { 
            Console.WriteLine(evens); 
        }
    }
}

Output:

14
28
40
4
16
30
42
6
18
32
44
8
20
34
46
10
22
36
48
12
24
38
50
26
Press any key to continue . . .

Explanation:

In the above program, we created the RandomEvens class that contains the Main() method.

IEnumerable Numbers = ((ParallelQuery)ParallelEnumerable.Range(1,50))
.Where(num => num % 2 == 0)
.Select(val => val);

Here we created integer numbers collection of IEnumerable type. Here we generated random even numbers. Then we printed the random even numbers between the range 1 to 50 on the console screen.

C# LINQ Programs »


ADVERTISEMENT
ADVERTISEMENT




Comments and Discussions!




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.