我必须读取一个CSV文件(这不是问题(并一次进行10次插入。我不知道CSV文件将有多少行。我尝试制作一个循环,每个 MOD 10 都会发送一个提交,但两三次后程序会出错。我不知道如何解决这个问题。
编辑:
对不起,我使用我的手机,我的代码是:
using (var connection = new SqliteConnection("conn-string"))
{
connection.Open();
using (var transaction = connection.BeginTransaction())
{
for (int i = 0; i < listCode.Count; i++)
{
string sql = $"insert into table1 (code) values ({listCode[i]})";
using (var command = new SqliteCommand(sql, connection))
{
command.ExecuteNonQuery();
if ( i % 10 == 9)
{
transaction.Commit();
}
}
}
}
}
这个问题现在已经过时了,因为家庭作业可能已经过去了。
但是,从代码中可以明显看出,第一次调用transaction.Commit();
时,事务将完成。 但是循环中没有启动新事务,因此下次调用transaction.Commit();
时将发生错误,因为将不再有活动事务!
此外,循环后没有代码来处理任何不能被 10 整除的残余行。 即使原始循环代码有效,它也可能留下未提交的行,这些行不会正确提交。
通常,如果要处理IEnumerable<T>
中的n
数量的项目,则可以结合使用IEnumerable
扩展方法,Skip
和Take
,其中跳过iteration * n
项,然后循环从列表中获取n
项。
请注意,如果我们在每次迭代时将循环变量递增 n
,那么这将成为我们传递给 Skip
的值。此外,如果剩余的项目少于 n
,Take(n)
将返回所有剩余项目。
例如:
// items would be the list of results from reading your csv file. Pseudocode:
List<SomeType> items = GetCSVItems(csvFilePath);
// Set this to the number of items we want to process in each batch
int batchCount = 10;
// To process a batch of 'batchCount' number of items, we first Skip(iteration * batchCount)
// items in our list, and then we Take(batchCount) items from the list for our next batch
for (int i = 0; i < items.Count; i += batchCount)
{
List<SomeType> itemBatch = items.Skip(i).Take(batchCount).ToList();
// Process itemBatch here
}
您可以使用库的扩展方法Batch
MoreLinq:将源序列批处理到大小的存储桶中。
如果你不想弄乱外部库,你可以使用以下方法,这是Batch
的轻量级版本。
public static IEnumerable<IEnumerable<TSource>> BatchForward<TSource>(
this IEnumerable<TSource> source, int size)
{
if (source == null) throw new ArgumentNullException(nameof(source));
if (size <= 0) throw new ArgumentOutOfRangeException(nameof(size));
var counter = 0;
var batchVersion = 0;
using (var enumerator = source.GetEnumerator())
{
while (enumerator.MoveNext())
{
counter++;
batchVersion++;
if ((counter - 1) % size == 0)
yield return GetInnerEnumerable(enumerator, batchVersion);
}
batchVersion++;
}
IEnumerable<TSource> GetInnerEnumerable(IEnumerator<TSource> enumerator, int version)
{
while (true)
{
if (version != batchVersion)
throw new InvalidOperationException("Enumeration out of order.");
yield return enumerator.Current;
if (counter % size == 0) break;
if (!enumerator.MoveNext()) break;
counter++;
};
}
}
使用示例:
foreach (var batch in Enumerable.Range(1, 22).BatchForward(5))
{
Console.WriteLine($"{String.Join(", ", batch)}");
}
输出:
1, 2, 3, 4, 5
6, 7, 8, 9, 10
票价:11、12、13、14、15
票价:16、17、18、19、20
元 21, 22