Friday October 9th

Thursday October 8th

3 Kicks

A LINQ Operator to Select Multiple Values from Sequences

Language-Integrated Query (LINQ) includes several projection operators but none that allow multiple items to be created from each item in a sequence. This article describes a custom operator that allows several selections to be made per item.


Very informative as usual :-)
Thanks for walking us through the code, the solution is much simpler than I would have guessed.

You can easily achieve the same result with SelectMany:

IEnumerable<string> people = couples.SelectMany(c => new[] { c.Person1, c.Person2 });

That's true. The reason I like SelectMulti (and I was considering just calling it Select, but didn't want to cause confusion when providing a single Func delegate) because I think it expresses intention better. It also provides a small benefit over the SelectMany approach in that if you have a large number of selector functions they won't all get called if the sequence isn't fully enumerated. So in the simple example I could be looking for a particular person. If that person was found in the Person1 property, I would not have evaluated the Person2 property. In the SelectMany version, all elements of the array must be evaluated, even if not needed. It's trivial in the Couples example but if the functions were expensive, or had side-effects (yeuch - I know), it could matter.

I also like the reusable validation and the encapsulation in a method. This wouldn't be so easy using SelectMany if you wanted to maintain the ability to have as many selectors as desired.

Commenting on Stories is limited for now and will open up to those recommended by the community. Learn how
Loading DotNetKicks...
brought to you by the Kicks Network