6

C# Program to Generate Random Even Numbers Using LINQ Parallel Query

 11 months ago
source link: https://www.geeksforgeeks.org/c-sharp-program-to-generate-random-even-numbers-using-linq-parallel-query/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

C# Program to Generate Random Even Numbers Using LINQ Parallel Query

LINQ is known as Language Integrated Query and was introduced in .NET 3.5. It gives power to .NET languages to generate or create queries to retrieve data from the data source. In this article, we will generate random even numbers in parallel using LINQ. So, we will use ParallelQuery{TSource} to generate a sequence of integral numbers in parallel within the given range. Along with it, we have to use the where and select clause to get the even numbers. Remember that it will throw an ArgumentOutOfRangeException if the stop is less than 0 or start +stop-1 is greater than the MaxValue.

Syntax:

IEnumerable<int> variable = ((ParallelQuery<int>)ParallelEnumerable.Range(start,
                            stop)).Where(x => x % 2 == 0).Select(i => i);

Where the start is the first integer value in the sequence and the stop is the number of sequential integers to generate.

Example:

Input  : Range(start, stop) = Range(1, 20)
Output :
2
6
12
16
4
8
14
18
10
20

Input  : Range(start, stop) = Range(10, 20)
Output :
10
12
14
16
18
20
22
24
26
28

Approach:

To print even numbers in parallel follow the following steps:

  1. Implement a parallelQuery{TSource} and mention the range.
  2. Use where clause to check the modulus of y by 2 is equal to zero.
  3. Now Select is used to check if the value of the j variable is greater than or equal to the value of the variable(i.e., j).
  4. Iterate the even numbers using the foreach loop

Example:

// C# program to generate random even numbers
// using LINQ Parallel Query
using System;
using System.Collections.Generic;
using System.Linq;
class GFG{
static void Main(string[] args)
{
// Creating data
IEnumerable<int> data = ((ParallelQuery<int>)ParallelEnumerable.Range(
// Condition for generating even numbers
10, 20)).Where(i => i % 2 == 0).Select(
value => value);
// Display even numbers
foreach(int even in data)
{
Console.WriteLine(even);
}
}
}

Output:


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK