说我有以下的code(上下文范围缩小到保持的问题包括但不限于)
Say I have the following code (context narrowed down as to keep the question scope limited)
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);
}
}
我想将它们改写为这样的事情(这当然不编译
I would like to rewrite them to something like this (which off course doesn't compile
public static IEnumerable<Color> GetThemColors(){
GetThePrimaryIds().Select(id=>yield return GetColorById(id));
GetTheOtherIds().Select(id=>yield return GetOtherColorsById(id));
}
关键的一点是,在我的第一个片段,我有两个的foreach枚举屈服,我不知道该怎么办的LINQ没有失去我的懒加载功能。
The key point being that in my first snippet I have two foreach enumerators yielding, which I don't know how to do in linq without loosing my lazy-loading features.
您想要 Concat的
:
return GetThePrimaryIds().Select(id => GetColorById(id)).Concat(
GetTheOtherIds().Select(id => GetOtherColorsById(id)));
另外请注意,你并不需要在lambda表达式收益率回报
。