All of the examples for SelectMany I see are flattening arrays of arrays and so on. I have a different angle on this question.
I have an array of a type, and I want to extract that type's contents into a stream. Here's my example code:
public class MyClass
{
class Foo
{
public int X, Y;
}
static IEnumerable<int> Flatten(Foo foo)
{
yield return foo.X;
yield return foo.Y;
}
public static void RunSnippet()
{
var foos = new List<Foo>()
{
new Foo() { X = 1, Y = 2 },
new Foo() { X = 2, Y = 4 },
new Foo() { X = 3, Y = 6 },
};
var query = foos.SelectMany(x => Flatten(x));
foreach (var x in query)
{
Console.WriteLine(x);
}
}
}
This outputs what I'd like: 1, 2, 2, 4, 3, 6.
Can I eliminate the yields? I know that the plumbing to support that is nontrivial, and probably has a significant cost. Is it possible to do it all in linq?
I feel like I'm very close to the answer and am just missing the magic keyword to search on. :)
UPDATE:
As mentioned in the answer below, it works to use something like this:
foos.SelectMany(x => new[] { x.X, x.Y });
However, I was hoping to find a way to do this without generating n/2 temporary arrays. I'm running this against a large selection set.