Last active
July 3, 2019 01:53
-
-
Save PassiveModding/4472291c0d2fa6277ec817d85973e63b to your computer and use it in GitHub Desktop.
Extension method for splitting a collection into chunks based on the cumulative value of some property in each chunk
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
public static IEnumerable<IEnumerable<T>> SplitList<T>(this IEnumerable<T> list, Func<T, int> sumComparator, int maxGroupSum) | |
{ | |
var subList = new List<T>(); | |
int currentSum = 0; | |
foreach (var item in list) | |
{ | |
//Get the size of the current item. | |
var addedValue = sumComparator(item); | |
//Ensure that the current item will fit in a group | |
if (addedValue > maxGroupSum) | |
{ | |
//TODO: add options to skip fields that exceed the length or add them as a solo group rather than just error out | |
throw new InvalidOperationException("A fields value is greater than the maximum group value size."); | |
} | |
//Add group to splitlist if the new item will exceed the given size. | |
if (currentSum + addedValue > maxGroupSum) | |
{ | |
//splitList.Append(subList); | |
yield return subList; | |
//Clear the current sum and the subList | |
currentSum = 0; | |
subList = new List<T>(); | |
} | |
subList.Add(item); | |
currentSum += addedValue; | |
} | |
//Return any remaining elements | |
if (subList.Count != 0) | |
{ | |
yield return subList; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
each chunk should have a cumulative size that is less than or equal to the specified max length. eg.
would give a collection with the following values:
the sum of the lengths of strings in each chunk are less than (or equal to) 7