拆分列表为N大小的小名单 [英] Split a List into smaller lists of N size

查看:159
本文介绍了拆分列表为N大小的小名单的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图名单分成一系列较小的列表。

我的问题:我的功能分割清单不会将它们分割成大小正确的名单。它应该将它们分为大小30名单而是将其他们分成大小114名单?

我怎样才能让我的功能拆分成列表大小名单的X个 30或更少

 公共静态列表<名单,LT;浮动[]>> splitList(列表<浮动[]>的位置,INT n大小= 30)
{
    清单<名单,LT;浮动[]>>名单=新名单<名单,LT;浮动[]>>();    的for(int i =(int)的(Math.Ceiling((十进制)(locations.Count / n大小))); I> = 0;我 - ){
        清单<浮动[]> subLocat =新的List<浮动[]>(位置);        如果(subLocat.Count> =((我* n大小)+ n大小))
            subLocat.RemoveRange(我* n大小,n大小);
        其他subLocat.RemoveRange(我* n大小,subLocat.Count-(我* n大小));        的debug.log(索引:+ i.ToString()+,尺寸:+ subLocat.Count.ToString());
        list.Add(subLocat);
    }    返回列表;
}

如果我使用功能尺寸144的名单则输出是:


  

指数:4,大小:120结果
  指数:3,大小:114结果
  指数:2,面积:114结果
  指数:1,尺寸:114结果
  指数:0,大小:114



解决方案

 公共静态列表<名单,LT;浮动[]>> splitList(列表<浮动[]>的位置,INT n大小= 30)
{
    VAR名单=新名单<名单,LT;浮动[]>>();    的for(int i = 0; I< locations.Count; I + = n大小)
    {
        list.Add(locations.GetRange(ⅰ,Math.Min(n大小,locations.Count - ⅰ)));
    }    返回列表;
}

I am attempting to split a list into a series of smaller lists.

My Problem: My function to split lists doesn't split them into lists of the correct size. It should split them into lists of size 30 but instead it splits them into lists of size 114?

How can I make my function split a list into X number of Lists of size 30 or less?

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;
}

If I use the function on a list of size 144 then the output is:

Index: 4, Size: 120
Index: 3, Size: 114
Index: 2, Size: 114
Index: 1, Size: 114
Index: 0, Size: 114

解决方案

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

    for (int i=0; i < locations.Count; i+= nSize) 
    { 
        list.Add(locations.GetRange(i, Math.Min(nSize, locations.Count - i))); 
    } 

    return list; 
} 

这篇关于拆分列表为N大小的小名单的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆