【问题标题】:Fill Enumerable Inside Enumerable in .NET 5 [closed]在 .NET 5 中的 Enumerable 中填充 Enumerable [关闭]
【发布时间】:2021-02-23 16:43:55
【问题描述】:

我有一个包含多个“面板页面”的“面板”模型。我想获取所有面板的列表,并用各自的“面板页面”填充每个面板。

这是我目前的代码(有效):

public IEnumerable<DynamicCustomPanel> GetCustomPanels()
{
    var customPanels = _customPanelService.GetDynamicCustomPanels();
    var dynamicCustomPanels = customPanels.ToList();

    foreach (var customPanel in dynamicCustomPanels.ToList())
    {
        var customPanelPages = _customPanelPageService.GetCustomPanelPages(customPanel.PanelGUID.ToString());
        customPanel.CustomPanelPages = customPanelPages;
    }

    return dynamicCustomPanels;
}

如何以最少的行数做到这一点?

【问题讨论】:

  • How do I do this in an minimal amount of lines? 是否存在问题,可能是维护或性能问题?
  • 摆脱那些额外的ToList() 电话。它们会消耗内存。

标签: c# linq .net-core ienumerable enumeration


【解决方案1】:

这应该可行:

public IEnumerable<DynamicCustomPanel> GetCustomPanels()
{
    return _customPanelService.GetDynamicCustomPanels().Select(p => {
         p.CustomPanelPages = _customPanelPageService.GetCustomPanelPages(p.PanelGUID.ToString());
         return p;
     });
}

这在技术上是 3 个语句(两个返回和一个赋值)和一个块,尽管它有点滥用 Select() 方法。我可能会这样写:

public IEnumerable<DynamicCustomPanel> GetCustomPanels()
{
    foreach(var p in _customPanelService.GetDynamicCustomPanels())
    {
        p.CustomPanelPages = _customPanelPageService.GetCustomPanelPages(p.PanelGUID.ToString());
        yield return p;
    }
}

这是...也是 3 个语句(计数 foreach)和一个块,只是间隔不同以使用多行文本。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-04-01
    • 1970-01-01
    • 2015-03-04
    • 2017-07-14
    • 1970-01-01
    • 2013-11-19
    • 2013-04-01
    • 2019-11-22
    相关资源
    最近更新 更多