开发者

How do I split a list based on index in C#?

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();


I've attempted a recursive approach. Just to see what it would look like.

List<List<T>> SplitIntoChunks<T>(IEnumerable<T> originalList, int chunkSize)
{
    if(originalList.Take(1).Count() == 0)
    {
        return new List<List<T>>();
    }

    var chunks = new List<List<T>> {originalList.Take(chunkSize).ToList()};
    chunks.AddRange(SplitIntoChunks(originalList.Skip(chunkSize), chunkSize));
    return chunks;
}


var list = new List<int>(Enumerable.Range(1,190));
var page_size = 50;
var max_pages = 1 + list.Count() / page_size;

for(int page = 1; page <= max_pages; page++) {
  var chunk = list.Skip(page_size * (page-1)).Take(page_size);
  // do whatever
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜