重写这个产量的foreach到LINQ的收益呢?
-
22-07-2019 - |
题
说我有以下代码(上下文缩小以保持问题范围的限制)
public static IEnumerable<Color> GetThemColors(){
var ids = GetThePrimaryIds();
foreach (int id in ids){
yield return GetColorById(id);
}
ids = GetTheOtherIds();
foreach (int id in ids){
yield return GetOtherColorsById(id);
}
}
我想将它们重写到这样的事情(其偏离方向不编译
public static IEnumerable<Color> GetThemColors(){
GetThePrimaryIds().Select(id=>yield return GetColorById(id));
GetTheOtherIds().Select(id=>yield return GetOtherColorsById(id));
}
关键的一点是,在我的第一个片段,我有两个的foreach枚举屈服,我不知道如何在LINQ做不失去我的懒加载功能。
解决方案
您想Concat
:
return GetThePrimaryIds().Select(id => GetColorById(id)).Concat(
GetTheOtherIds().Select(id => GetOtherColorsById(id)));
另外请注意,你不需要yield return
在lambda表达式。
不隶属于 StackOverflow