问题
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));
}
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.
回答1:
You want Concat:
return GetThePrimaryIds().Select(id => GetColorById(id)).Concat(
GetTheOtherIds().Select(id => GetOtherColorsById(id)));
Also note that you don't need yield return in lambdas.
来源:https://stackoverflow.com/questions/1824934/rewrite-this-foreach-yield-to-a-linq-yield