Home »
.Net »
C# Programs
C# - Generate random even numbers using LINQ Parallel Query
Learn, how to generate random even numbers using LINQ parallel query in C#?
By Nidhi Last updated : April 01, 2023
Generating random even numbers
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.
C# program to generate random even numbers using LINQ parallel query
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 »