A LINQ Operator to Select Multiple Values from Sequences

added by BlackWasp
9/4/2012 9:09:29 AM

3 Kicks, 275 Views

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.


9/4/2012 9:08:29 AM
Very informative as usual :-)
Thanks for walking us through the code, the solution is much simpler than I would have guessed.

9/4/2012 10:27:13 AM
You can easily achieve the same result with SelectMany:

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

9/4/2012 11:33:11 AM
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.