这个问题太简单了,只要用模运算即可快速解决,而且看你的需求,连拆分都不需要,直接原始List即可均分线程处理的。 方法如下: for(int i = 0; i<listStr.Count; i++) { Switch(i%N)//这里N为拆分数 { case 0: break; case 1: break; ... case N: break; default: break; } }
满足不了我的需求哦、我认真理解了你的代码、 我现在必须要用拆分list的方式来完成、 还请指点。
private List<string>[] GetList(List<string> listStr, int count) { int num = listStr.Count / count; int mod = listStr.Count % count; List<List<string>> result = new List<List<string>>(); int i = 0; while(i < listStr.Count) { int c = Math.Min(listStr.Count - i, num+(mod-- > 0 ? 1 : 0)); string[] temp = new string[c]; listStr.CopyTo(i, temp, 0, c); result.Add(temp.ToList()); i += c; } return result.ToArray(); }
如果不考虑顺序的话还可以这样private List<string>[] GetList(List<string> listStr, int count) { List<string>[] result = new List<string>[count]; for(int i=0; i<count; i++) { result[i] = new List<string>(); } for(int i=0; i<listStr.Count; i++) { result[i % count].Add(listStr[i]); } return result; }
private List<string>[] GetList(List<string> listStr, int count) { int len = listStr.Count / count; if (listStr.Count % count > 0) { ++len; } List<string>[] array = new List<string>[count]; int c = listStr.Count / len; int r = listStr.Count % len; int i = 0; for (; i < c; ++i) { array[i] = listStr.GetRange(i * len, len); } if (r > 0) { array[i] = listStr.GetRange(i * len, r); } return array; }
/// <summary>
/// 平均分流ListStr
/// </summary>
/// <param name="listStr">源list</param>
/// <param name="count">需要分为几份(这里也就是我程序中要创建几个线程、每个线程执行分好后的list)</param>
/// <returns>分好后的list<string>数组</returns>
private List<string>[] GetList(List<string> listStr, int count)
{
//考虑在不能被整除的情况下要进一
//其实我要做的就是把一个串list分为N个线程自行、具体分为几个线程由用户自定义。
}
不知道这么写能明白吗
考虑不能整除时需进1
方法如下:
for(int i = 0; i<listStr.Count; i++)
{
Switch(i%N)//这里N为拆分数
{
case 0:
break;
case 1:
break;
...
case N:
break;
default:
break;
}
}
我现在必须要用拆分list的方式来完成、
还请指点。
private List<string>[] GetList(List<string> listStr, int count)
{
int num = listStr.Count / count;
int mod = listStr.Count % count;
List<List<string>> result = new List<List<string>>();
int i = 0;
while(i < listStr.Count)
{
int c = Math.Min(listStr.Count - i, num+(mod-- > 0 ? 1 : 0));
string[] temp = new string[c];
listStr.CopyTo(i, temp, 0, c);
result.Add(temp.ToList());
i += c;
}
return result.ToArray();
}
{
List<string>[] result = new List<string>[count];
for(int i=0; i<count; i++)
{
result[i] = new List<string>();
}
for(int i=0; i<listStr.Count; i++)
{
result[i % count].Add(listStr[i]);
}
return result;
}
{
int len = listStr.Count / count;
if (listStr.Count % count > 0)
{
++len;
}
List<string>[] array = new List<string>[count];
int c = listStr.Count / len;
int r = listStr.Count % len;
int i = 0;
for (; i < c; ++i)
{
array[i] = listStr.GetRange(i * len, len);
}
if (r > 0)
{
array[i] = listStr.GetRange(i * len, r);
}
return array;
}