将列表拆分为N个较小的N列表

将列表拆分为N个较小的N列表

我试图将列表拆分成一系列较小的列表。

我的问题:我拆分列表的功能不会将它们拆分成正确大小的列表。它应该将它们分成大小为30的列表,而是将它们分成大小为114的列表?

如何使我的功能将列表拆分为X个大小为30或更小的列表?

public static List<List<float[]>> splitList(List <float[]> locations, int nSize=30) {       
    List<List<float[]>> list = new List<List<float[]>>();

    for (int i=(int)(Math.Ceiling((decimal)(locations.Count/nSize))); i>=0; i--) {
        List <float[]> subLocat = new List <float[]>(locations); 

        if (subLocat.Count >= ((i*nSize)+nSize))
            subLocat.RemoveRange(i*nSize, nSize);
        else subLocat.RemoveRange(i*nSize, subLocat.Count-(i*nSize));

        Debug.Log ("Index: "+i.ToString()+", Size: "+subLocat.Count.ToString());
        list.Add (subLocat);
    }

    return list;}

如果我在144的列表上使用该函数,那么输出是:

指数:4,大小:120 
指数:3,大小:114 
索引:2,大小:114 
索引:1,大小:114 
索引:0,大小:114


隔江千里
浏览 548回答 3
3回答

拉莫斯之舞

public&nbsp;static&nbsp;List<List<float[]>>&nbsp;splitList(List<float[]>&nbsp;locations,&nbsp;int&nbsp;nSize=30)&nbsp;&nbsp;{&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp;&nbsp;var&nbsp;list&nbsp;=&nbsp;new&nbsp;List<List<float[]>>();&nbsp; &nbsp;&nbsp;&nbsp;&nbsp;for&nbsp;(int&nbsp;i=0;&nbsp;i&nbsp;<&nbsp;locations.Count;&nbsp;i+=&nbsp;nSize)&nbsp; &nbsp;&nbsp;&nbsp;&nbsp;{&nbsp; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;list.Add(locations.GetRange(i,&nbsp;Math.Min(nSize,&nbsp;locations.Count&nbsp;-&nbsp;i)));&nbsp; &nbsp;&nbsp;&nbsp;&nbsp;}&nbsp; &nbsp;&nbsp;&nbsp;&nbsp;return&nbsp;list;&nbsp;}通用版本:public&nbsp;static&nbsp;IEnumerable<List<T>>&nbsp;splitList<T>(List<T>&nbsp;locations,&nbsp;int&nbsp;nSize=30)&nbsp;&nbsp;{&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp;&nbsp;for&nbsp;(int&nbsp;i=0;&nbsp;i&nbsp;<&nbsp;locations.Count;&nbsp;i+=&nbsp;nSize)&nbsp; &nbsp;&nbsp;&nbsp;&nbsp;{&nbsp; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;yield&nbsp;return&nbsp;locations.GetRange(i,&nbsp;Math.Min(nSize,&nbsp;locations.Count&nbsp;-&nbsp;i));&nbsp; &nbsp;&nbsp;&nbsp;&nbsp;}&nbsp;&nbsp;}

狐的传说

我建议使用此扩展方法将源列表按指定的块大小分块到子列表:/// <summary>/// Helper methods for the lists./// </summary>public static class ListExtensions{&nbsp; &nbsp; public static List<List<T>> ChunkBy<T>(this List<T> source, int chunkSize)&nbsp;&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; return source&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; .Select((x, i) => new { Index = i, Value = x })&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; .GroupBy(x => x.Index / chunkSize)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; .Select(x => x.Select(v => v.Value).ToList())&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; .ToList();&nbsp; &nbsp; }}例如,如果您将18个项目的列表按每个块5个项目进行分块,则会为您提供4个子列表的列表,其中包含以下项目:5-5-5-3。

阿晨1998

怎么样:while(locations.Any()){&nbsp;&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp;&nbsp;list.Add(locations.Take(nSize).ToList()); &nbsp;&nbsp;&nbsp;&nbsp;locations=&nbsp;locations.Skip(nSize).ToList();}
打开App,查看更多内容
随时随地看视频慕课网APP