2014-10-28 70 views
0

很多时候,我的清单过于庞大,我不得不把它们分成批处理。如何分批处理IEnumerable?

有没有一种方法可以在方法或扩展中封装它。我似乎必须在任何地方编写这个批处理逻辑。

const int TAKE = 100; 
int skip = 0; 
while (skip < contacts.Count) 
{ 
    var batch = contacts.Skip(skip).Take(TAKE).ToList(); 
    DoSomething(batch); 
    skip += TAKE; 
} 

我愿做这样的事情 -

Batch(contacts, DoSomething); 

或任何类似,所以我不必一次又一次地写这个批处理逻辑。

回答

1

使用批处理解决方案从this thread似乎微不足道:

const int batchSize = 100; 

foreach (var batch in contacts.Batch(batchSize)) 
{ 
    DoSomething(batch); 
} 

如果你也想包起来:

public static void ProcessInBatches<TSource>(
       this IEnumerable<TSource> source, 
       int batchSize, 
       Action<IEnumerable<TSource>> action) 
{ 
    foreach (var batch in source.Batch(batchSize)) 
    { 
     action(batch); 
    } 
} 

所以,你的代码可被转换成:

const int batchSize = 100; 

contacts.ProcessInBatches(batchSize, DoSomething);