我有以下内容:
blocks.Where(x => x.BlockName == NAVIGATION)
.ForEach(block => block.Data = db.Pages.Select(x => x.Name).ToList());
如果
where
找到多个块,那么如何防止db.Pages.Select
对每个块执行数据库命中,而又将List
重用于第二个块和后续块。lambda函数中可以有静态变量吗?
更新:如果
where
找到零个块,我根本不想执行获取。更新:blocks是一个内存列表
最佳答案
var blocksResult = blocks.Where(x => x.BlockName == NAVIGATION);
if (blocksResult.Any())
{
var blockData = db.Pages.Select(x => x.Name).ToList();
blocksResult.ForEach(block => block.Data = blockData);
}
要么
List<string> blockData = null;
blocks.Where(x => x.BlockName == NAVIGATION).ForEach(block => block.Data = (blockData ?? (blockData = db.Pages.Select(x => x.Name).ToList())))