Saturday, July 21, 2018
c# - Nested yield return with IEnumerable
Answer
Answer
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
.
private static IEnumerable GetErrors(Card card)
{
var errors = GetMoreErrors(card);
foreach (var e in errors)
yield return e;
// further yield returns for more validation errors
}
Is it possible to return all the errors in GetMoreErrors
without having to enumerate through them?
Thinking about it this is probably a stupid question, but I want to make sure I'm not going wrong.
Answer
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.
plot explanation - Why did Peaches' mom hang on the tree? - Movies & TV
In the middle of the movie Ice Age: Continental Drift Peaches' mom asked Peaches to go to sleep. Then, she hung on the tree. This parti...
-
This question attempts to collect the few pearls among the dozens of bad C++ books that are published every year. Unlike many other programm...
-
I am new to dask and I found so nice to have a module that makes it easy to get parallelization. I am working on a project where I was able ...
-
Award winning movie director, producer, and writer, who is best known for movies Blue Velvet, Dune, and Mulholla...
No comments:
Post a Comment