LINQ / IEnumerable Skip () Efficiency of Take () when used with "yield return"

I have a question about efficiency Skip()and Take()when using c IEnumerable<>.

I return all my data lists with IEnumerable<>, and I use "return return" so that there is no need to allocate large amounts of memory for data transfer. It works very efficiently.

However, later, in my process, I wanted to buy this data and take blocks of about 20 entries from my list at a time. I thought to myself ... ah! This is great for an enumerator.

I found very useful methods on Skip()and Take()on IEnumerable interface, but now I understand that this causes my Loop to re-interact from the very beginning every time.

What is the best way to swap data from IEnumerable? Should I use MoveFirst()and MoveNext()in the enumerator instead of Skip()and Take()?

I have done several searches, but cannot find the answer.

Can anyone help?

I really like the functionality LINQon IEnumerable<>, but I really have to consider efficiency.

+4
source share
2 answers

Batch, , :

public static IEnumerable<IEnumerable<T>> Batch<T>(
    this IEnumerable<T> source, int batchSize)
{
    List<T> buffer = new List<T>(batchSize);

    foreach (T item in source)
    {
        buffer.Add(item);

        if (buffer.Count >= batchSize)
        {
            yield return buffer;
            buffer = new List<T>(batchSize);
        }
    }
    if (buffer.Count > 0)
    {
        yield return buffer;
    }
}
+6

. , Skip, .

, . , , , "" , ?

IEnumerable, (, LINQ) , , , . . 10, , 5 60 . 3 , . 10 .

, , , - . IEnumerable<T> IEnumerator<T> .

0

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


All Articles