1

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 ?

1

2 Answers 2

5

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.

Sign up to request clarification or add additional context in comments.

4 Comments

Also I don't think while fits into a query expression... it is easily confused with a regular "imperative" while construct.
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).
@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 :)
Hehe, let's say my general opinion on VBs syntax is not of the positive kind.
0

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.

2 Comments

-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.
My bad – I misread it as trying to take the first 100 Fibonacci numbers.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.