Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
C# Program to Generate Odd Numbers in Parallel using LINQ
This article demonstrates how to generate odd numbers in parallel using LINQ in C#. LINQ (Language Integrated Query) provides a powerful way to query data from collections, arrays, and databases using a SQL-like syntax. When combined with parallel processing, LINQ can efficiently handle large datasets by distributing work across multiple CPU cores.
Syntax
Following is the syntax for generating odd numbers in parallel using LINQ
IEnumerable<int> odds = ParallelEnumerable.Range(start, count)
.Where(x => x % 2 != 0)
.Select(x => x);
LINQ Methods Used
Where() Method
The Where() method filters elements based on a Boolean condition (predicate). It returns only those elements for which the condition evaluates to true.
Select() Method
The Select() method projects each element of a sequence into a new form. In this case, it selects the filtered odd numbers.
Example
The following example generates odd numbers in parallel within the range 10 to 20
using System;
using System.Linq;
using System.Collections.Generic;
class Program {
static void Main(string[] args) {
// Generate odd numbers in parallel within range 10 to 20
IEnumerable<int> oddNumbers = ParallelEnumerable.Range(10, 11)
.Where(x => x % 2 != 0)
.Select(x => x);
Console.WriteLine("Odd numbers generated in parallel:");
foreach (int number in oddNumbers) {
Console.WriteLine(number);
}
}
}
The output of the above code is
Odd numbers generated in parallel: 11 13 15 17 19
Using AsParallel() for Existing Collections
You can also apply parallel processing to existing collections using the AsParallel() method
using System;
using System.Linq;
class Program {
static void Main(string[] args) {
int[] numbers = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
var oddNumbers = numbers.AsParallel()
.Where(x => x % 2 != 0)
.Select(x => x * x); // Square the odd numbers
Console.WriteLine("Squared odd numbers:");
foreach (int number in oddNumbers) {
Console.WriteLine(number);
}
}
}
The output of the above code is
Squared odd numbers: 1 9 25 49 81
Performance Comparison
| Approach | Processing Type | Best For |
|---|---|---|
| LINQ (Sequential) | Single-threaded | Small datasets, simple operations |
| PLINQ (Parallel) | Multi-threaded | Large datasets, CPU-intensive operations |
| ParallelEnumerable.Range() | Parallel from start | Generating sequences in parallel |
Conclusion
Parallel LINQ (PLINQ) in C# enables efficient processing of large datasets by distributing operations across multiple CPU cores. Using methods like ParallelEnumerable.Range(), Where(), and Select(), you can generate and filter data in parallel, significantly improving performance for computationally intensive tasks.
