我想知道,是否有一种优雅的方法可以从通用集合(在我的例子中是 List<T> )中删除多个项目,而无需执行某些操作,例如在 LINQ 查询中指定谓词以查找要删除的项目?
我正在做一些批处理,其中我正在填充 List<T>与 Record需要处理的对象类型。此处理以将每个对象插入数据库结束。我不想构建列表,然后遍历每个成员并处理/插入它,而是想对 N 组执行事务性批量插入列表中的项目,因为它占用的资源较少(其中 N 表示我可以放入配置文件或等效文件中的 BatchSize)。
我想做类似的事情:
public void ProcessRecords()
{
// list of Records will be a collection of List<Record>
var listOfRecords = GetListOfRecordsFromDb( _connectionString );
var batchSize = Convert.ToInt32( ConfigurationManager.AppSettings["BatchSize"] );
do
{
var recordSubset = listOfRecords.Take(batchSize);
DoProcessingStuffThatHappensBeforeInsert( recordSubset );
InsertBatchOfRecords( recordSubset );
// now I want to remove the objects added to recordSubset from the original list
// the size of listOfRecords afterwards should be listOfRecords.Count - batchSize
} while( listOfRecords.Any() )
}
我正在寻找一种一次性完成所有操作的方法,而不是遍历子集并以这种方式删除项目,例如:
foreach(Record rec in recordSubset)
{
if( listOfRecords.Contains(rec) )
{
listOfRecords.Remove(rec);
}
}
我正在考虑使用 List.RemoveRange( batchSize ) ,但想先获得一些 StackOverflow 反馈 :) 您使用什么方法来最大限度地提高 C# 批处理算法的效率?
非常感谢任何帮助/建议/提示!
请您参考如下方法:
有扩展方法
public static IEnumerable<List<T>> ToBatches<T>(this List<T> list, int batchSize)
{
int index = 0;
List<T> batch = new List<T>(batchSize);
foreach (T item in list)
{
batch.Add(item);
index++;
if (index == batchSize)
{
index = 0;
yield return batch;
batch = new List<T>(batchSize);
}
}
yield return batch;
}
您可以将输入序列分成批处理:
foreach(var batch in listOfRecords.ToBatches(batchSize))
{
DoProcessingStuffThatHappensBeforeInsert(batch);
InsertBatchOfRecords(batch);
}
