I have a list with around 190 elements in it for now. How can I split the list into smaller lists with a max of 50 elements in each list?
The result could be lists of 50, 50, 50 and 40 elements.
Assuming you mean List<T>
, you can use the GetRange
method repeatedly. Heck, you could do this with LINQ:
var lists = Enumerable.Range(0, (list.Count + size - 1) / size)
.Select(index => list.GetRange(index * size,
Math.Min(size, list.Count - index * size)))
.ToList();
Or you could just use a loop, of course:
public static List<List<T>> Split(List<T> source, int size)
{
// TODO: Validate that size is >= 1
// TODO: Prepopulate with the right capacity
List<List<T>> ret = new List<List<T>>();
for (int i = 0; i < source.Count; i += size)
{
ret.Add(source.GetRange(i, Math.Min(size, source.Count - i)));
}
return ret;
}
This is somewhat more efficient than using GroupBy
, although it's limited to List<T>
as an input.
We have another implementation using IEnumerable<T>
in MoreLINQ in Batch.cs.
You could use LINQ:
var list = Enumerable.Range(1, 190);
var sublists = list
.Select((x, i) => new { Index = i, Value = x })
.GroupBy(x => x.Index / 50)
.Select(x => x.Select(v => v.Value).ToList())
.ToArray();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With