2

如何以另一种 .SelectMany() 形式编写此 LINQ 表达式?

var result = 
                    from a in numbersA
                    where a < 3
                    from b in numbersB
                    where b < 5
                    select new { a, b };

?

var result = numbersA.Where(x => x < 3).Select.. ?

4

2 回答 2

4

这是编译器会做什么的粗略翻译:

var result = numbersA.Where(a => a < 3)
                     .SelectMany(a => numbersB, (a, b) => new { a, b })
                     .Where(z => z.b < 5)
                     .Select(z => new { z.a, z.b });

现在您可以更有效地编写如下:

var result = numbersA.Where(a => a < 3)
                     .SelectMany(a => numbersB.Where(b => b < 5),
                                 (a, b) => new { a, b });

...但这不是编译器会做的。目前尚不清楚您的目标是查看编译器的功能,还是只是编写查询。

于 2012-10-18T15:45:32.067 回答
3

就像是

var result = numbersA.Where(a => a < 3).SelectMany(a =>
    numbersB.Where(b => b < 5).Select(b => new { a, b }));

numbersB 请注意,只过滤一次可能更有效:

var filteredB = numbersB.Where(b => b < 5).ToArray();
var result = numbersA.Where(a => a < 3).SelectMany(a =>
    filteredB.Select(b => new { a, b }));
于 2012-10-18T15:42:57.793 回答