本文介绍了尼斯,干净的交叉只使用扩展方法Linq中加入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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
        });
}
解决方案

One way would be:

var z2 = xs.SelectMany(x => ys, (x, y) => new {x, y});

这篇关于尼斯,干净的交叉只使用扩展方法Linq中加入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-05 03:08