Skip to content

Instantly share code, notes, and snippets.

@PassiveModding
Last active July 3, 2019 01:53
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save PassiveModding/4472291c0d2fa6277ec817d85973e63b to your computer and use it in GitHub Desktop.
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
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;
}
}
@PassiveModding
Copy link
Author

each chunk should have a cumulative size that is less than or equal to the specified max length. eg.

            var strings = new string[]{"hey","how","are","you","today","friend"};
            var groupedStrings = SplitList(strings, x => x.Length, 7);

would give a collection with the following values:

[
  [
    "hey",
    "how"
  ],
  [
    "are",
    "you"
  ],
  [
    "today"
  ],
  [
    "friend"
  ]
]

the sum of the lengths of strings in each chunk are less than (or equal to) 7

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment