Property with Enumerable or list

I play with LINQ and related topics and wonder about the following.

I have 2 methods to get the Fibonacci sequence. I started with:

public static IEnumerable<int> Fibonacci
    {
        get
        {
            int i = 0;
            int j = 1;
            int temp = 0;

            while (true)
            {
                yield return i;

                temp = i;
                i = j;
                j = temp + i;
            }
        }
    }  

But it made me wonder: why should I choose this:

public static IList<int> Fibonacci(long to)
    {            
        IList<int> fibList = new List<int>();
        int i = 0;
        int j = 1;
        int temp, index = 0;

        while (index < to)
        {
            fibList.Add(i);

            temp = i;
            i = j;
            j = temp + i;

            index++;
        }
        return fibList;
    }

IList is also enumerated, and I can add some parameterization to it. I'm really not looking for optimizations or things or things, long> because the number is getting very fast, this is just a quick example. Just some pro and con arguments of each method. Why and when should I use which method?

+3
source share
3 answers

, , , , . .

. .

, , . , , , , , .

, , . , .

, Fibinocci().Take(20).ToList().

+4

( ). , ...? , , - "" /, .

0

If you put the first version in foreach, then it will never end unless you break out. Potential source of error when using it. This may be what you want, but it is something to be wary of.

0
source

Source: https://habr.com/ru/post/1729695/


All Articles