我有一个列表,目前我们一次只将一个项目传递给另一个方法
foreach (var contact in tracker.Parse())基本上,我们从Azure Blob存储中选择联系人并将其导入Dynamics CRM。tracker.Parse()返回的是联系人列表。
我希望每隔1000次选择一次,然后等待它们在另一种方法中完成,然后再传入下一个1000。
需要关于如何做到这一点的指导。
感谢您的帮助!
发布于 2017-03-21 07:44:51
将数据源中的数据分组为所需的组大小,并对其进行处理。
使用Linq可以通过Select和GroupBy扩展来实现
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);
}
}发布于 2017-03-21 06:52:29
也许就像这样..。
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));
}https://stackoverflow.com/questions/42915251
复制相似问题