我有一个包含100万个元素的数组,需要将这些元素分成每组100个,并执行一个函数,然后继续处理下一百个元素。
foreach (string value in lines)
{
filescreated++;
if (filescreated == ?????????)
{
do stuff
}
}
????等于可被100整除的值
我有一个包含100万个元素的数组,需要将这些元素分成每组100个,并执行一个函数,然后继续处理下一百个元素。
foreach (string value in lines)
{
filescreated++;
if (filescreated == ?????????)
{
do stuff
}
}
????等于可被100整除的值
foreach (...)
{
filescreated++;
if (filescreated % 100 == 0)
{
// do stuff for the every 100th element
}
// do other stuff for every element
}
参考: 模数 (%
) 运算符
如果您需要针对每个第100个元素执行特殊操作,但仍需要处理每个元素,请使用此功能。
如果您只需要处理每100个元素,请参考Reed的回答。
如果您需要按顺序并且百分比对您不好,那么怎么办?
这个问题很困惑,因为您谈论每一百个元素,然后又谈论100个一组。所以这里只能猜测。
string[] lines = new string[1000000];
for (int i = 0; i < 10000; i++)
{
for (int j = 0; j < 100; j++)
{
DoSomething(lines[100*i + j], i);
}
}
int chunkSize = 100;
for (int start=0; start<lines.Length;start += chunkSize)
{
ProcessSectionOfArray(lines, start, Math.Min(start+chunkSize-1, lines.Length-1));
}
// A separate static function
private static IEnumerable<IEnumerable<T>> BreakIntoBlocks<T>(T[] source, int blockSize)
{
for (int i = 0; i < source.Length; i += blockSize)
{
yield return source.Skip(i).Take(blockSize);
}
}
// And in your code
string[] lines = new string[1000000];
foreach(IEnumerable<string> stringBlock in BreakIntoBlocks(lines, 100))
{
// stringblock is a block of 100 elements
// Here is where you put the code that processes each separate group
}
上述尝试应该比我的第一次尝试(如下)更快
int blockSize = 100;
int i = 0;
IEnumerable<IEnumerable<string>> query = from s in lines
let num = i++
group s by num / blockSize into g
select g;
foreach(IEnumerable<string> stringBlock in query)
{
// Stringblock will be a block of 100 elements.
// Process this 100 elements here.
}