问题描述
我有一个具有多个“面板页面”的“面板”模型。我想获得所有面板的列表,并用各自的“面板页面”填充每个面板。
这是我目前的代码(有效):
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
)和一个块,只是间隔不同以使用多一行文本。