问题
Possible Duplicate:
Nested “from” LINQ query expressed with extension methods
I'm sure this has been asked before, but I honestly couldn't find anything.
I'm curious what the equivalent syntax would be for the following using only built-in Linq extension methods:
var z1 =
    from x in xs
    from y in ys
    select new { x, y };
I can get the same results with this:
var z2 = xs.SelectMany(x => ys.Select(y => new { x, y }));
But it produces different IL code, and the code is a bit convoluted and hard to understand. Is there a cleaner way to do this with extension methods?
Here's my entire test method as written:
private void Test()
{
    var xs = new[] { 1D, 2D, 3D };
    var ys = new[] { 4D, 5D, 6D };
    var z1 =
        from x in xs
        from y in ys
        select new { x, y };
    var z2 = xs.SelectMany(x => ys.Select(y => new { x, y }));
}
Here's the [Edit: C# interp of the] IL code (using ILSpy):
private void Test()
{
    double[] xs = new double[]
    {
        1.0, 
        2.0, 
        3.0
    };
    double[] ys = new double[]
    {
        4.0, 
        5.0, 
        6.0
    };
    var z =
        from x in xs
        from y in ys
        select new
        {
            x = x,
            y = y
        };
    var z2 = xs.SelectMany((double x) =>
        from y in ys
        select new
        {
            x = x,
            y = y
        });
}
    回答1:
One way would be:
var z2 = xs.SelectMany(x => ys, (x, y) => new {x, y});
    回答2:
If you really want to use a single LINQ extension method, then another candidate would be Join, with the outerKeySelector and innerKeySelector functions defined such that they will always produce equal values.
var z3 = xs.Join(ys, x => true, y => true, (x, y) => new { x, y });
This will, however, probably give more convoluted IL code than the nested from solution. Incidentally, MSDN uses the nested from in its example for a cross join; look at the first code snippet in How to: Perform Custom Join Operations (C# Programming Guide).
来源:https://stackoverflow.com/questions/9120318/nice-clean-cross-join-in-linq-using-only-extension-methods