Use PLINQ to select even numbers from an array in C#

This example is really a demonstration of PLINQ, since you probably won't need to use this technique to find even numbers. (If you do need to generate even numbers, it'll be a lot faster and easier to simply pick random numbers and then double them.)

Parallel LINQ (PLINQ), which enables LINQ to use multiple cores or CPUs if your computer has them, is remarkably easy to use. Simply add a call to the AsParallel method to whatever collection of objects your LINQ query is searching.

This example generates an array of random numbers. It then uses LINQ and PLINQ to search the array for even numbers. The following code shows the LINQ query.

var linq_query =
    from int number in numbers
    where number % 2 == 0
    select number;

The following code shows the PLINQ query with the call to AsParallel highlighted in bold.

var plinq_query =
    from int number in numbers.AsParallel()
    where number % 2 == 0
    select number;

It's that simple!

If you look closely at the program's image, you'll see that searching 10 million random numbers took 0.40 seconds using LINQ but only 0.27 seconds using PLINQ. My computer is a dual-core system so PLINQ is considerably faster. The overhead required to use both cores slows things down a bit so the PLINQ query doesn't take exactly half as long as the LINQ query, but the speed up is considerable.

(The example program contains other code that times the queries and displays up to 1,000 numbers in each ListBox. Download the example to see additional details.)



What did you think of this article?

  • No trackbacks exist for this post.

  • 1/15/2014 1:21 PM Scott wrote:
    Change the 'where' to this:

    where (number & 0x01) == 0

    More often than not, you'll see substantial gains.
    Reply to this
    1. 1/16/2014 2:15 PM Rod Stephens wrote:
      True. In this example, I save about 20% of the time. It's a nice change!

      In general I try to avoid tricks like this that make the code a bit harder to read. But if you're looking at a really big array, you may want to do this. (Add a comment to make it easier to figure out what the code is doing.)
      Reply to this
Leave a comment

Submitted comments are subject to moderation before being displayed.


 Email (will not be published)


Your comment is 0 characters limited to 3000 characters.