Bor*_*ens 6 .net c# linq yield lazy-loading
假设我有以下代码(上下文缩小以保持问题范围有限)
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);
}
}
Run Code Online (Sandbox Code Playgroud)
我想把它们改写成这样的东西(当然不会编译
public static IEnumerable<Color> GetThemColors(){
GetThePrimaryIds().Select(id=>yield return GetColorById(id));
GetTheOtherIds().Select(id=>yield return GetOtherColorsById(id));
}
Run Code Online (Sandbox Code Playgroud)
关键点在于,在我的第一个片段中,我有两个foreach枚举器屈服,我不知道如何在linq中做什么而不会丢失我的延迟加载功能.
Pav*_*aev 15
你想要Concat:
return GetThePrimaryIds().Select(id => GetColorById(id)).Concat(
GetTheOtherIds().Select(id => GetOtherColorsById(id)));
Run Code Online (Sandbox Code Playgroud)
另请注意,yield returnlambda中不需要.