【问题标题】:Select every 1000 items from a list and pass it to a method从列表中选择每 1000 个项目并将其传递给方法
【发布时间】:2017-03-20 22:38:39
【问题描述】:

我有一个列表,目前我们一次将一个项目传递给另一个方法

foreach (var contact in tracker.Parse())

基本上,我们从 Azure Blob 存储中选择联系人并将其导入 Dynamics CRM。 tracker.Parse() 返回的是联系人列表。

我想每 1000 个选择一次,然后等到它们在其他方法中完成,然后再传入下一个 1000 个。

需要有关如何执行此操作的指导。

感谢您的帮助!

【问题讨论】:

标签: c#


【解决方案1】:

将数据源中的数据分组到所需的组大小并进行处理。

使用 Linq 可以通过 SelectGroupBy 扩展来实现

int groupSize = 1000;

//Batch the data
var batches = tracker.Parse()
  .Select((contact, index) => new { contact, index })
  .GroupBy(_ => _.index / groupSize, _ => _.contact);

//Process the batches.
foreach (var batch in batches) {
    //Each batch would be IEnumerable<TContact>
    ProcessBatch(batch);
}

如果需要,这可以转换为可重用的泛型方法

public static void ProcessInBatches<TItem>(this IEnumerble<TItem> items, int batchSize, Action<IEnumerable<TItem>> processBatch) {

    //Batch the data
    var batches = items
      .Select((item, index) => new { item, index })
      .GroupBy(_ => _.index / batchSize, _ => _.item);

    //Process the batches.
    foreach (var batch in batches) {
        //Each batch would be IEnumerable<TItem>
        processBatch(batch);
    }
}

【讨论】:

    【解决方案2】:

    也许是这样的......

    static void Main()
    {
        const int batchSize = 1000;
    
        // Populate array with 5841 items of data
        var lotsOfItems = new List<int>();
        for (int i = 0; i < 5841; i++)
        {
            lotsOfItems.Add(i);
        }
    
        // Process items in batches, waiting for each batch to complete before the next
        int indexOfLastItemTaken = 0;
        while (indexOfLastItemTaken < lotsOfItems.Count - 1)
        {
            var itemsTaken = lotsOfItems.Skip(indexOfLastItemTaken).Take(batchSize).ToList();
            ProcessItems(itemsTaken);
            indexOfLastItemTaken += itemsTaken.Count();
        }
    
        Console.Write("Done. Press any key to quit...");
        Console.ReadKey();
    }
    
    static void ProcessItems(IEnumerable<int> input)
    {
        // do something with input
        Console.WriteLine(new string('-', 15));
        Console.WriteLine($"Processing a new batch of {input.Count()} items:");
        Console.WriteLine(string.Join(",", input));
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-07-19
      • 2021-01-05
      • 2016-08-22
      • 1970-01-01
      • 2016-10-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多