有没有人发现/编码扩展方法批量查询数据(使用
linq到sql)?我已经看过IEnumerable扩展,但我正在寻找我可能会使用的东西:
- IQueryable<Order> orders = from i in db.Orders select i;
- foreach(var batch in orders.InBatches(100))
- {
- //batch of 100 products
- foreach(var order in batch)
- {
- //do something
- }
- }
解决方法
你能做的是:
- public static IEnumerable<IQueryable<T>> InBatches(
- this IQueryable<T> collection,int size)
- {
- int totalSize = collection.Count();
- for (int start = 0; start < totalSize; start += size)
- {
- yield return collection.Skip(start).Take(size);
- }
- }
此扩展方法允许您对返回IQueryables执行额外的过滤器.但是,实用性非常有限.我想不出任何好的情况:-).在大多数情况下,您只想流式传输结果并返回IEnumerable< IEnumerable< T>>只会做得很好,甚至更好,因为这将导致单个SQL查询,而显示的方法将导致N 1个查询.