문제

다음 코드가 있다고 가정 해

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

핵심 요점은 첫 번째 스 니펫에는 두 개의 foreach 열거자가 생성된다는 것입니다. 이는 게으른로드 기능을 잃지 않고 LINQ에서해야 할 방법을 모릅니다.

도움이 되었습니까?

해결책

당신은 원합니다 Concat:

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

또한 필요하지 않습니다 yield return 람다에서.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top