我有一个项目列表,例如
id 1 2 3 4 5 6 7 8 9 10 11 12 13
我想将其写入 csv,并以 5 为一组进行,因此当它达到 id 5 时,它将转到下一批。我正在考虑做 mod 来满足这个需求,所以
int noOfIds = MyIDList.Count % 5; // to get the number of loops i need
List<MyIDList> topFiveID = (from c in MyIDList
select c).Take(5).ToList(); // get top 5 from the list
然后我得到休息
List<MyIDList> restOfIDs = MyIDList.Where(c => !topFiveID.Any(tc => tc.ID == c.ID)).ToList();
现在我可以看到它最多可以满足 9 个 ID,有人可以告诉我如何满足所有 ID 的需求,无论有多少个 ID。
希望它足够清楚。
最佳答案
以下将从枚举中返回给定大小的批处理:
public static IEnumerable<IEnumerable<TSource>> Batch<TSource>(
this IEnumerable<TSource> source,
int batchSize)
{
var batch = new List<TSource>();
foreach (var item in source)
{
batch.Add(item);
if (batch.Count == batchSize)
{
yield return batch;
batch = new List<TSource>();
}
}
if (batch.Any()) yield return batch;
}
像这样使用:
foreach (var list in MyIdList.Batch(5))
{
// list is an IEnumerable<T> containing up to 5 items
Console.WriteLine("{0}", String.Join(",", list));
}
关于c# - 将项目分成一批数字以获取 csv,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13383807/