Return all enumerables with yield return at once; without looping through

前端 未结 6 1707
甜味超标
甜味超标 2020-11-29 03:55

I have the following function to get validation errors for a card. My question relates to dealing with GetErrors. Both methods have the same return type IEnumerable&

6条回答
  •  孤街浪徒
    2020-11-29 04:28

    You could set up all the error sources like this (method names borrowed from Jon Skeet's answer).

    private static IEnumerable> GetErrorSources(Card card)
    {
        yield return GetMoreErrors(card);
        yield return GetOtherErrors();
        yield return GetValidationErrors();
        yield return AnyMoreErrors();
        yield return ICantBelieveHowManyErrorsYouHave();
    }
    

    You can then iterate over them at the same time.

    private static IEnumerable GetErrors(Card card)
    {
        foreach (var errorSource in GetErrorSources(card))
            foreach (var error in errorSource)
                yield return error;
    }
    

    Alternatively you could flatten the error sources with SelectMany.

    private static IEnumerable GetErrors(Card card)
    {
        return GetErrorSources(card).SelectMany(e => e);
    }
    

    The execution of the methods in GetErrorSources will be delayed too.

提交回复
热议问题