在.net 5的Enumerable中填充Enumerable



我有一个" panel ";具有多个"面板页"的模型。我想得到所有面板的列表,并填写每个面板各自的"面板页"。

下面是我当前的代码:

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

我如何在最少的行数中做到这一点?

应该可以:

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)和一个块,只是间距不同,以便多使用一行文本。

最新更新