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


Introduction

In this article we will learn how to write a C# program that uses LINQ parallel query to generate random even numbers. Let's quickly review the language. The C# programming language is basically used to create desktop, internet, and mobile apps. Linguistic Integrated Query, also known as LINQ, is one of the advantages of C#. Developers may quickly access data from a variety of sources, including arrays, collections, and databases. Regardless of the data source, it offers a standard syntax for data queries. As LINQ and SQL share a similar syntax, developers can use and understand them both easily.

Problem Explanation

Let's create a program that generates random even numbers using LINQ parallel query for better understanding. In this problem, it gives a number of options for querying objects that use ParallelQuery TSource to generate random even numbers in parallel using LINQ, which must be done as the first step of every application. Also, we need to use the Where and Select clauses in order to get the random even numbers.

To finish this task, the following two LINQ clause will be applied −

  • Select()

  • Where()

Let's now briefly discuss both clauses.

Select()

In LINQ parallel queries, the "select" clause is used to reshape the outcomes of a query into a new form. It is frequently used to describe the structure and elements of the returned results set from a query. Here is an example of how to use a LINQ parallel query's "select" clause.

Int[] num = {1, 2, 3, 4,5};
Var query = from n in num.AsParallel()
   where n % 2 ==0
   Select n * n; 

The 'AsParallel() method will be used to parallelize a LINQ query in this example. We select the numbers array to only contain even integers using the "where" clause, and we then project the results by squaring each number using the "select" clause

The squared values of the even numbers in the "numbers" array will be put into a "IEnumerable" that is stored in the resulting "query" variable.

Remember that when we are using the ‘select’ clause in a parallel LINQ query, It is important to ensure that the projection operation is thread-safe and does not depend on the order of the input data. If the projection operation is not thread-safe or depends on the order of the input data, the results of the query may be incorrect or unpredictable.

Where()

The "where" clause in a LINQ parallel query is used to filter the elements of a collection according to a given condition. It allows you to specify a specific criterion for paring down the result set of a query. Here’s an example of using the ‘where’ clause in a LINQ parallel query.

Int[] num = {1, 2, 3, 4,5};
Var query = from n in num.AsParallel()
   where n % 2 == 0
   Select n;

In this example, the LINQ query is made parallel using the 'AsParallel()' method. Next, using the "where" clause, we will select the "numbers" array to only include even integers.

The 'IEnumerableint>' in the resulting 'query' variable will only contain the even numbers from the 'numbers' array.

Remember that when using the ‘where’ clause in a parallel LINQ query, it is important to ensure that the condition is thread-safe and does not depend on the order of the input data. The output of the query may be incorrect or unclear if the condition is not thread-safe or dependent on the sequence of the input data.

Syntax using Where and Select

To generate even random numbers using a LINQ parallel query in a C# program, we will use the where and select clauses. Below is the syntax that uses the where and select clauses to resolve the problem.

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

Here, in this case ‘start’ is the first integer value of the sequence and ‘stop’ is the number of sequential integers to generate.

Always keep in mind that if the stop is less than 0 or the start + stop-1 is larger than the MaxValue, an ArgumentOutOfRangeException will be thrown.

To better understand the problem, let's have look at an example −

Example

Let's say we need to generate parallel sets of random even numbers inside a given range. As a result, we must specify the range (10, 20) and find all the random even numbers that fall within it.

Input

Range(start, stop) = Range(10, 20) 

We must create all the random even numbers within the range of numbers we presently have, which is clearly defined. As a result, our output will look like this −

Output

1612
14
18
10
20
1416
12
20
10
18

Algorithm

The time complexity of C# program to generate a random even numbers in the range(10, 20) using LINQ parallel query can be analyzed using the following algorithms −

Step 1  Firstly we calculate the number of even numbers in the range(10,20) = 5.

Step 2  Now we will create a parallel query that generates 5 random even numbers using PLINQ.

Step 3  The overhead of the PLINQ parallel query is constant and can be ignored for small inputs.

Step 4 − The time complexity of generating each random even number is O(1).

Step 5  Therefore, the time complexity of the entire program is O(5*1) = O(1).

Example

using System;
using System.Linq;

class TutorialPoint {
   static void Main(string[] args) {
      
      // Calculate the number of even numbers in the range (10, 20)
      int numEven = Enumerable.Range(10, 11).Count(i => i % 2 == 0);
      
      // Generate 5 random even numbers in parallel using PLINQ
      var evenNum = Enumerable.Range(10, 11)
                              .Where(i => i % 2 == 0)
                              .AsParallel() 
                              .OrderBy(i => Guid.NewGuid())
                              .Take(numEven);
      
      // Print the generated even numbers
      foreach (var i in evenNum) {
         Console.WriteLine(i);
      }
   }
}
  • Here, the "Enumerable.Range" approach is chosen in this code to generate a sequence of integers in the specified range (10, 20).

  • The range's even numbers are counted using the 'Count' function.

  • The odd integers are filtered out using the 'Where' approach.

  • The ‘AsParallel’ method is used to create a parallel query.

  • The ‘OrderBy’ method is used to shuffle the even numbers, and

  • The ‘Take’ method is used to take the required number of even numbers. Finally,

  • The ‘foreach’ loop is used to print the generated even numbers.

Output

20
12
16
18
10
14

Time Complexity

The time complexity of a C# a program to generate random even numbers in the range (10, 20) using a LINQ parallel query is O(1). This is because the range is fixed and small (only 5 numbers), and generating a random even number in this range involves a constant time operation.

However, if the range is increased, the time complexity will depend on the number of elements in the range and the overhead of the LINQ parallel query. If the range is large, the time complexity may be O(n/log n), where n is the number of elements in the range. This is because the LINQ parallel query divides the range into smaller partitions, which are processed in parallel, thus reducing the overall time complexity

Conclusion

In this article we have discussed extensively the C# program to generate random even numbers using LINQ parallel query. Before we jump on code, we make sure that we will be able to understand the problem and have discussed the syntax and clauses that we are going to use in the program, especially the select and where clauses. We have also learned about the algorithms and the code in depth for better understanding, And have generated the relevant output of the code. At last we have learned about its time complexity in detail. We hope that this article will be useful in enhancing your knowledge in C# programs.

Updated on: 04-Apr-2023

475 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements