我有以下内容:

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())))

10-04 12:19