c# – 用于批量获取数据的IQueryable扩展方法

前端之家收集整理的这篇文章主要介绍了c# – 用于批量获取数据的IQueryable扩展方法前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
有没有人发现/编码扩展方法批量查询数据(使用 linqsql)?我已经看过IEnumerable扩展,但我正在寻找我可能会使用的东西:
  1. IQueryable<Order> orders = from i in db.Orders select i;
  2. foreach(var batch in orders.InBatches(100))
  3. {
  4. //batch of 100 products
  5. foreach(var order in batch)
  6. {
  7. //do something
  8. }
  9. }

解决方法

你能做的是:
  1. public static IEnumerable<IQueryable<T>> InBatches(
  2. this IQueryable<T> collection,int size)
  3. {
  4. int totalSize = collection.Count();
  5.  
  6. for (int start = 0; start < totalSize; start += size)
  7. {
  8. yield return collection.Skip(start).Take(size);
  9. }
  10. }

此扩展方法允许您对返回IQueryables执行额外的过滤器.但是,实用性非常有限.我想不出任何好的情况:-).在大多数情况下,您只想流式传输结果并返回IEnumerable< IEnumerable< T>>只会做得很好,甚至更好,因为这将导致单个SQL查询,而显示方法将导致N 1个查询.

猜你在找的C#相关文章