简体   繁体   English

列表中的项目计数未按预期工作

[英]Counting of items in list not working as expected

I have a list which contains 91 items in it.我有一个列表,其中包含 91 项。 I currently loop over and write each line to a text file using StreamWriter .我目前使用StreamWriter循环并将每一行写入文本文件。 I want to divide the list by 3 so after 30 items I want to insert a blank line.我想将列表除以 3,所以在 30 个项目之后我想插入一个空行。 So far I have到目前为止我有

foreach (var item in textList)
{
   //write to file
   counter++;
   if (counter == totalItems / 3)
   {
      await sw.WriteLineAsync(Environment.NewLine);
   }
}

but it only works for the first 30 items.但它仅适用于前 30 个项目。 Please note the list can contain any number of items but this particular one contains 91. However I will always have to divide into 3.请注意,该列表可以包含任意数量的项目,但这个特定的项目包含 91 个。但是我总是必须分成 3 个。

You either want to divide a list of 91 items by 3 or after 30 items.您要么希望将 91 个项目的列表除以 3,要么将其划分为 30 个项目。 You can't have both.你不能两者兼得。 If you do it after every 30 items, you would have the 91st item separated from the rest, on its own 'chunk', i,e.如果您在每 30 个项目之后执行此操作,那么您会将第 91 个项目与 rest 分开,在其自己的“块”上,即1-30, 31-60, 61-90, 91. If you have 91 items, and want to split by 3, you should do it every 31 items (hence why I am using Math.Ceiling ). 1-30, 31-60, 61-90, 91. 如果你有 91 个项目,并且想除以 3,你应该每 31 个项目做一次(这就是我使用Math.Ceiling )。 That way you'd have 1-31, 32-62 and 63-91.这样你就有 1-31、32-62 和 63-91。

Also, don't use foreach AND a counter;另外,不要使用foreach和计数器; use the for loop instead.改用for循环。 And you can use the modulus operator.您可以使用模数运算符。 As so:如此:

int third = Convert.ToInt32(Math.Ceiling(textList.Count / 3.0));
int divider = third - 1;

for (int i = 0; i < textList.Count; i++)
{
    var itemToWrite = textList[i];
    //write to file

    if (i % third == divider) await sw.WriteLineAsync(Environment.NewLine);
}

Use modulo.使用模数。 Try like:试试看:

 if (counter % (totalItems / 3) == 0)
 {
   ...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM