在foreach循环中迭代IQueryable

时间:2018-11-09 12:36:30

标签: c# entity-framework

具有这样的代码

foreach (Order order in dbContext.Orders)
{
    // some operations
}

每次迭代后是否从db中获取订单? 是否有必要在ToList()上致电dbContext.Orders

1 个答案:

答案 0 :(得分:1)

它不会在foreach循环的每次迭代中加载一个订单。枚举时,您的代码会将整个查询结果加载到内存中。

如果您在List()上使用IQueryable<Order>,则无需foreach输入ToList()类型。当您调用foreach或使用import pygame import os import random from pygame.locals import * # Constants import math import sys import random pygame.init() screen=pygame.display.set_mode((1280,720)) #(length,height) screen_rect=screen.get_rect() background = pygame.Surface(screen.get_size()) background = pygame.image.load('stage.png').convert() screen.blit(background, (0, 0)) class Player(pygame.sprite.Sprite): def __init__(self): self.rect = pygame.draw.rect(screen, (0,0,128), (50,560,50,25)) #(colour)(x-position,y-position,width,height) self.dist = 100 def draw_rect(self,x,y): # This is my code which should make the player move screen.blit(background, (0, 0)) #If this isn't included then when the rectangle moves it's old positon will still be on the screen self.rect = self.rect.move(x*self.dist, y*self.dist); pygame.draw.rect(screen, (0, 0, 128), self.rect) pygame.display.update() def handle_keys(self): # code to make the character move when the arrow keys are pressed keys = pygame.key.get_pressed() if keys[K_LEFT]: self.draw_rect(-0.05,0) elif keys[K_RIGHT]: self.draw_rect(0.05,0) elif keys[K_UP]: self.draw_rect(0,-0.05) elif keys[K_DOWN]: self.draw_rect(0,0.05) elif keys[K_SPACE]: self.draw_rect(0.05,-0.05) if self.rect.right > 1280: self.rect.right = 1280 if self.rect.left < 0: self.rect.left = 0 if self.rect.bottom > 720: self.rect.bottom = 720 if self.rect.top < 0: self.rect.top = 0 class Enemy(pygame.sprite.Sprite): # the enemy class which works fine def __init__(self): x = random.randint(50,450) self.rect = pygame.draw.rect(screen, (128,0,0), (300,x,50,25)) player = Player() enemy = Enemy() def main(): #my main loop running = True while running: player.handle_keys() for event in pygame.event.get(): if event.type == pygame.QUIT: running = False pygame.display.flip() #updates the whole screen if __name__ == '__main__': main() 循环时,查询将被优化。

查看有关Query Execution

的更多信息