Justin Etheredge’s LINQ Challenge
- You have to blog about a single LINQ query which starts with Enumerable.Range(1,n) and produces a list of prime numbers from the range.
- You can’t cheat. This is determined by me, and includes hardcoding values in the results. You’ll know if you cheated.
- Uses no custom LINQ methods.
- Will return all of the prime numbers of the sequence. It doesn’t have to be super optimal, but it has to be correct.
- Be one of the first 5 people to blog a correct answer and then tweet this "I just solved the @tekpub LINQ challenge: <link to post>" will get any single TekPub screencast. The time of your solution will be based on your tweet! So be prompt!
- You must link to both TekPub’s website and this post in your blog post.
I can’t resist a good brainteaser, so here’s my answer. I’m sure it’s not the most efficient way of solving the problem, but it works:
var max = ...; var primes = Enumerable.Range(1, max) .Where(x => x != 1 &&
!Enumerable.Range(2, (int)Math.Sqrt(x)).Any(y => x != y && x % y == 0));
But, I’ve already got a subscription to TekPub, so I don’t need the prize! Instead, I’m going to give it away to the first person who comments on this post. If you haven’t seen TekPub yet, you should check it out! It’s a great resource for programmers of all levels of skill.