micahhoover micahhoover - 3 months ago 43
C# Question

iterating with Linq

I am trying to find a way to access previous values from a Linq method in the same line.

I want to be able to use this general form in Linq:

var values = Enumerable.Range( 1, 100 ).Select( i => i + [last result] );

But I can't find a way to do something like this without multi-line lambda's and storing the results somewhere else.

So the best fibonacci sum I've been able to do in Linq is:

List<int> calculated = new List<int>( new int[] { 1, 2 });
var fibonacci = Enumerable.Range(2, 10).Select(i =>
int result = calculated[i - 2] + calculated[i - 1];
return result; // and how could I just put the result in fibonacci?

Which seems ugly. I could do this in less code with a regular for loop.

for (int i = 2; i < 10; i++)
calculated.Add(calculated[i - 2] + calculated[i - 1]);

It seems like if I could find a way to do this, I could use Linq to do a lot of Linear programming and sum a lot of iterative formulas.


If you are looking for a way to create a Fibonacci sequence generator, you would be better off writing your own generator function instead of using Linq extension methods. Something like this:

public static IEnumerable<int> Fibonacci()
    int a = 1;
    int b = 0;
    int last;

    for (;;) {
        yield return a;

        last = a;
        a += b;
        b = last;

Then you can apply Linq methods to this enumerable to achieve the result you want (try iterating over Fibonacci().Take(20) for example).

Linq extension methods are not the solution for every programming problem, and I can only imagine how horrid a pure LINQ Fibonacci sequence generator would look.