Skip to content
Related Articles

Related Articles

Improve Article
Save Article
Like Article

C# Program to Generate Odd Numbers in Parallel using LINQ

  • Last Updated : 21 Oct, 2021

LINQ is known as Language Integrated Query and it is introduced in .NET 3.5. It gives the ability to .NET languages to generate queries to retrieve data from the data source. It removes the mismatch between programming languages and databases and the syntax used to create a query is the same no matter which type of data source is used. In this article, we will generate odd numbers in parallel using LINQ. So, we will use ParallelQuery{TSource} to generate odd numbers in parallel. Along with it, we have to use the where and select clause to get the odd numbers

Syntax:

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

Examples:

Input: Range(start, stop)= Range(10,11)
Output:
13
17
19
11
15

Input: Range(start, stop)= Range(5,8)
Output:
11
5
7
9

Approach: To print odd numbers in parallel follow the following steps:

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

Example: 

C#




// C# program to print odd numbers in parallel 
// Using LINQ
using System;
using System.Linq;
using System.Collections.Generic;
   
class GFG{
      
static void Main(string[] args)
{
      
    // Implement parallel Query in the range 10 to 11
    IEnumerable<int> odd = ((ParallelQuery<int>)ParallelEnumerable.Range(10, 11))
      
    // condition to check for the odd numbers
    .Where(y => y % 2 != 0)
      
    // Select that odd numbers
    .Select(j => j);
      
    // Display the odd numbers
    foreach (int n in odd) 
    
        Console.WriteLine(n);
    }
    Console.ReadLine();
}
}

Output:

13
17
19
11
15
My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!