我在数据库中有一个包含3000多行的表格。
我想在字符串数组中获取单列详细信息,我需要将此数组发送给第三方api,但数组长度不应超过1000。
所以我需要根据记录发送3/4个不同的数组
string[] deviceIds = FirebaseNotificationList.Select(x => x.DeviceID).ToArray();我需要将string[] deviceIds划分为长度为1000的不同字符串数组
如果我使用下面的代码,它将只占用前1000行:
string[] deviceIds = FirebaseNotificationList
.Select(x => x.DeviceID).Take(1000).ToArray();我应该如何做到这一点而不遗漏任何行?
发布于 2017-04-05 19:09:15
您可以使用Select方法重载,它为结果选择器提供元素的索引。然后,按index/batchSize进行简单的分组会将您的所有项目分成所需大小的批次:
int batchSize = 1000;
var batches = FirebaseNotificationList
.Select((fn,i) => new { fn.DeviceID, i })
.GroupBy(x => x.i / batchSize)
.Select(g => g.Select(x => x.DeviceID).ToArray());您还可以使用MoreLINQ Batch来避免创建匿名对象,因为匿名对象在源列表中保存有关其索引的信息
var batches = FirebaseNotificationList
.Select(fn => fn.DeviceID)
.Batch(batchSize); // note that batches will be IEnumerable<T>发布于 2017-04-05 19:12:43
批量处理可以通过Linq实现,如下所示。
int BatchSize = 1000;
IEnumerable<string> Tail = DeviceIds;
while (Tail.Count() > 0)
{
var Head = Tail.Take(BatchSize);
// process Head
Tail = Tail.Skip(BatchSize);
}发布于 2017-04-05 19:15:23
这个问题已经在:Create batches in linq上得到了回答
public static class MyExtensions
{
public static IEnumerable<IEnumerable<T>> Batch<T>(this IEnumerable<T> items,
int maxItems)
{
return items.Select((item, inx) => new { item, inx })
.GroupBy(x => x.inx / maxItems)
.Select(g => g.Select(x => x.item));
}
}它的用法是:
List<int> list = new List<int>() { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
foreach(var batch in list.Batch(3))
{
Console.WriteLine(String.Join(",",batch));
}输出:
0,1,2
3,4,5
6,7,8
9个
https://stackoverflow.com/questions/43229385
复制相似问题