Split a list into equal parts that using LINQ in a way that has good performance So I have a method that looks like this:

   public static List&lt;List&lt;List&lt;string&gt;&gt;&gt; Split(List&lt;List&lt;string&gt;&gt; source, int chunksize)
   {
       return source
           .Select((x, i) =&gt; new { Index = i, Value = x })
           .GroupBy(x =&gt; x.Index / chunksize)
           .Select(x =&gt; x.Select(v =&gt; v.Value).ToList())
           .ToList();
   }


While this is nice and elegant and readable, unfortunately that groupby is killing performance because of the implicit sort. I need a way to rewrite this to be more performant, while still being reasonably elegant.
We can make the method more generic:

public static IEnumerable&lt;IEnumerable&lt;T&gt;&gt; Split&lt;T&gt;(IEnumerable&lt;T&gt; source, int chunkSize)
{


Then we can store the current chunk in a List&lt;T&gt;. Using the constructor that takes the initial capacity should be good for performance:

    var chunk = new List&lt;T&gt;(chunkSize);
    foreach (var item in source)
    {
        chunk.Add(item);
        if (chunk.Count == chunkSize)
        {
            yield return chunk;
            chunk.Clear();
        }
    }


Finally we need to return the final (non-empty) chunk

    if (chunk.Count &gt; 0)
    {
        yield return chunk;
    }
}


Depending on your use case, you might want to make a copy of the list and yield return chunk.ToList() instead.