0

i have list . which contains 13 list elements. i want to get first four elements , then next foour element and so on

2
Contributors
1
Reply
7
Views
3 Years
Discussion Span
Last Post by deceptikon
0

This is an extension method I use for that purpose:

/// <summary>
/// Separates a list of items into sub-lists of chunkSize chunks.
/// </summary>
/// <param name="items">The original list of items.</param>
/// <param name="chunkSize">The desired size of each sub-list.</param>
/// <returns>A list of sub-lists of up to size chunkSize.</returns>
public static List<List<T>> Chunk<T>(this List<T> items, int chunkSize)
{
    if (!items.Any())
    {
        return new List<List<T>>();
    }

    var result = new List<List<T>>();
    var currentList = new List<T>();
    int i = 0;

    result.Add(currentList);

    foreach (T item in items)
    {
        if (i >= chunkSize)
        {
            currentList = new List<T>();
            result.Add(currentList);
            i = 0;
        }

        currentList.Add(item);
        i += 1;
    }

    return result;
}
This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.