Created
November 10, 2017 10:17
-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/// <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