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

前端 未结 6 1693
甜味超标
甜味超标 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:22

    It's definitely not a stupid question, and it's something that F# supports with yield! for a whole collection vs yield for a single item. (That can be very useful in terms of tail recursion...)

    Unfortunately it's not supported in C#.

    However, if you have several methods each returning an IEnumerable, you can use Enumerable.Concat to make your code simpler:

    private static IEnumerable GetErrors(Card card)
    {
        return GetMoreErrors(card).Concat(GetOtherErrors())
                                  .Concat(GetValidationErrors())
                                  .Concat(AnyMoreErrors())
                                  .Concat(ICantBelieveHowManyErrorsYouHave());
    }
    

    There's one very important difference between the two implementations though: this one will call all of the methods immediately, even though it will only use the returned iterators one at a time. Your existing code will wait until it's looped through everything in GetMoreErrors() before it even asks about the next errors.

    Usually this isn't important, but it's worth understanding what's going to happen when.

提交回复
热议问题