Mastering LINQ

Mastering LINQ is a new series on Tekpub.com, the Rob Conery site with, yet few, but very interesting screencast about new technologies.

 

The host of Mastering LINQ, Justin Etheredge,  posted a challenge on his site  promising the first five people to code a LINQ  query returning all primes of a sequence a single Tekpub screencast of choice.

 

I gave it a try! It is really easy:

var n = 100;
var primes = Enumerable.Range(1, n)
    .Where(i => i > 1)
    .Where(i =>
               {
                   for (int j = 2; j <= Math.Sqrt(i); j++)
                   {
                       if (i%j == 0)
                           return false;
                   }
                   return true;
               }
    );

 

Having a yearly subscription of Tekpub I don’t really need the price. I will give it away to some co-worker probably.

UPDATE:

The closure inside the where function could also be formulated using the “Range” and “All” method of the (I)Enumerable:

var primes2 = Enumerable.Range(1, n)
    .Where(i => i > 1)
    .Where(i => Enumerable
                    .Range(2, (int) Math.Sqrt(i) - 1)
                    .All(mod => i%mod != 0)
    );

January 9, 2010 |
Tags : Challenge LINQ Programming

About Me

Moukarram Kabbash This blog is kept alive by me, Moukarram Kabbash, a programmer, hobby photographer from Dortmund in Germany.

mouk.github.com