tags:

views:

87

answers:

2

Having

public static IEnumerable<long> FibonacciNumbers() {
 long current = 0;
 long next = 1;

 while (true) {
  long previous = current;
  current = next ;
  next = previous + next;
  yield return current;
 }
}

I can get the first fibonacci numbers less that 100 with

var series = FibonacciNumbers().TakeWhile(num => num < 100);

Just being curious, how would I do that using query syntax ?

+3  A: 

You wouldn't - there's nothing in C# query expressions that corresponds to TakeWhile (or Take, Skip, SkipWhile etc). C# query expressions are relatively limited, but cover the biggies:

  • Select (via select and let)
  • Where (via where)
  • SelectMany (via secondary from clauses)
  • OrderBy/ThenBy (and descending) (via orderby clauses)
  • Join (via join clauses)
  • GroupBy (via groupby clauses)
  • GroupJoin (via join ... into clauses)

VB 9's query support is a bit more extensive, but personally I like C#'s approach - it keeps the language relatively simple, but you can still do everything you want via dot notation.

Jon Skeet
Also I don't think while fits into a query expression... it is easily confused with a regular "imperative" while construct.
Skurmedel
I personally don't like the C# approach but I agree with you. I don't like making the language look like FoxPro. I wish C# did not have that syntax at all (I agree it sometimes looks better).
Mehrdad Afshari
@Skurmedel: TakeWhile is in VB9's query support; I don't think it's really *bad*, but not particularly necessary. @Mehrdad: I like it for joins and anywhere that transparent identifiers are introduced. In fact, I've got a new section in C# in Depth 2nd edition discussing pros and cons :)
Jon Skeet
Hehe, let's say my general opinion on VBs syntax is not of the positive kind.
Skurmedel
A: 

There's no built in syntax for this in LINQ. Besides, writing it in LINQ would be more verbose and wouldn't really aid clarity, so there's no real need in this case.

Also, you should use Take rather than TakeWhile here.

Will Vousden
-1 for suggesting using Take. The point of using TakeWhile is to keep going until he reaches a Fibonacci number greater than or equal to 100. He can't predict how many elements that will be (without prior knowledge of the Fibonacci sequence). TakeWhile is exactly what's required.
Jon Skeet
My bad – I misread it as trying to take the first 100 Fibonacci numbers.
Will Vousden
Removed downvote then :)
Jon Skeet