Rewrite this foreach yield to a linq yield?

雨燕双飞 提交于 2019-12-01 17:41:12

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!