【问题标题】:Rewrite this foreach yield to a linq yield?将此 foreach 收益率重写为 linq 收益率?
【发布时间】:2010-12-21 22:46:11
【问题描述】:

假设我有以下代码(上下文缩小以限制问题范围)

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));       
}

关键在于,在我的第一个 sn-p 中,我有两个 foreach 枚举器产生,我不知道如何在 linq 中做到这一点而不会失去我的延迟加载功能。

【问题讨论】:

    标签: c# .net linq lazy-loading yield


    【解决方案1】:

    你想要Concat:

    return GetThePrimaryIds().Select(id => GetColorById(id)).Concat(
        GetTheOtherIds().Select(id => GetOtherColorsById(id)));
    

    另请注意,您不需要在 lambdas 中使用 yield return

    【讨论】:

    • 谢谢,没有意识到 concat 很懒
    • 据我所知,所有返回 IEnumerable 的 Enumerable 方法都是惰性的。
    • 是的,但我认为出于某种原因 Concat 会返回一个 IList
    • 需要注意的是,对GetTheOtherIds()的调用是not惰性的,即先调用GetThePrimaryIds(),再调用GetTheOtherIds(),再调用Concat() .但是,如果方法本身是惰性的,那么这不是问题。
    • @borisCallens:如果是这样,它会被声明为返回 IListICollection
    猜你喜欢
    • 2011-05-14
    • 2013-09-28
    • 2012-11-26
    • 2014-03-21
    • 2020-08-04
    • 1970-01-01
    • 2015-04-29
    • 2011-04-20
    • 1970-01-01
    相关资源
    最近更新 更多