Skip to content

Instantly share code, notes, and snippets.

@romeshniriella
Created November 10, 2017 10:17
Show Gist options
  • Save romeshniriella/dbfe1fa2af24f8563d3327c46887dbc6 to your computer and use it in GitHub Desktop.
Save romeshniriella/dbfe1fa2af24f8563d3327c46887dbc6 to your computer and use it in GitHub Desktop.
Break a list of items into (N) number of lists with the last list containing all the items that weren't in the 1st.
/// <summary>
/// given the list of items [1,2,3] and the count 2,
/// break the list into 2 lists containing 1 in 1st list and 2,3 in 2nd list and so on.
/// </summary>
/// <typeparam name="T">type</typeparam>
/// <param name="items">item list</param>
/// <param name="listCount">no of lists to produce</param>
/// <returns>listCount no of lists containing the items. last list contains the rest</returns>
public static List<List<T>> ToChunks<T>(this IEnumerable<T> items, int listCount)
{
var result = new List<List<T>>();
var list = items.ToList();
var div = (listCount > list.Count ? list.Count : listCount);
var chunkSize = list.Count / (div <= 0 ? 1 : div);
var total = 1;
while (list.Count > 0)
{
if (total < listCount)
{
var temp = list.Take(chunkSize).ToList();
result.Add(temp);
list.RemoveRange(0, temp.Count);
}
else
{
result.Add(list.Take(list.Count).ToList());
list.Clear();
}
total++;
}
return result;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment