【问题标题】:How to use bulk insert condition for particular number of records inside for loop如何在for循环中对特定数量的记录使用批量插入条件
【发布时间】:2020-05-28 17:11:08
【问题描述】:

一旦计数达到 20,我想在 C# 中使用批量插入概念。如果我们有 40 个数字没有问题。但是如果我们得到 39 条记录就有问题,这取决于条件。我们如何能够避免这个问题。下面我添加了一个简单的程序供参考。

var numbers = 39  // not static numbers
int count = 0;
for(int i=0; i<=numbers; i++)
{

 count++;
 if (count == 20)
   {
      //Logic
      count = 0;
   }

}

【问题讨论】:

  • 你的 for 循环是从零开始的吗?
  • 是循环从零开始

标签: c# .net for-loop asp.net-core


【解决方案1】:

您可以通过将计数器与剩余文件数进行比较来确定是否批量插入剩余文件。

int num = 49;
int count = 0;
for(int i = 1; i <= num; i++)
{
    count++;
    var n = i / 20;
    if(i % 20 == 0 ||count == (num - 20 * ( i / 20)))
    {
        //Logic        
        count = 0;
    }
}

【讨论】:

    【解决方案2】:

    不需要count变量,可以在for循环中使用modulo operator

    喜欢

    for(int i = 0; i <= numbers; i++)
    {
        //i != 0 to avoid bulk process at first
        if(i != 0 && i % 20 == 0)
        {
           //Your bulk operation
        }
    
    }
    

    我建议您在每次迭代中使用Console.WriteLine() 打印icounter 的值,以便您了解代码中的错误。

    var numbers = 39  // not static numbers
    int count = 0;
    for(int i=0; i<=numbers; i++)
    {
    
     count++;
    
     //Print values to understand flow of program 
     Console.WriteLine($"For i = {i}, value of count is {count}");
    
     if (count == 20)
       {
          Console.WriteLine("Time to reset count variable");
          //Logic
          count = 0;
    
       }
    
    }
    

    你可以使用Linq.Skip().Take(),做批处理

    var batchSize = 20;
    var batchCount = files.Count() / batchSize;
    for (int i = 0; i < batchCount; i++)
    {
      var bulkFiles = files.Skip(i * batchSize).Take(batchSize);
    }
    

    【讨论】:

    • 我更新了我的答案,请检查。同时删除不必要的 cmets。这样可以避免别人混淆
    猜你喜欢
    • 1970-01-01
    • 2011-02-20
    • 1970-01-01
    • 1970-01-01
    • 2020-03-18
    • 1970-01-01
    • 1970-01-01
    • 2023-04-03
    • 1970-01-01
    相关资源
    最近更新 更多