c #ForEach中的静态成员

时间:2015-07-23 07:38:58

标签: c# foreach lambda static

我有以下内容:

blocks.Where(x => x.BlockName == NAVIGATION)
      .ForEach(block => block.Data = db.Pages.Select(x => x.Name).ToList());

如果where找到多个块,我怎样才能阻止db.Pages.Select为每个块执行数据库命中,只需将List重用于第二个和后续块。< / p>

你能在lambda函数中有静态变量吗?

更新:如果where找到零块,我根本不想执行提取。

UPDATE:blocks是内存列表

1 个答案:

答案 0 :(得分:3)

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);
}

OR

List<string> blockData = null;
blocks.Where(x => x.BlockName == NAVIGATION).ForEach(block => block.Data = (blockData ?? (blockData  = db.Pages.Select(x => x.Name).ToList())))