LINQ扩展方法.SelectMany()以另一种形式编写

时间:2012-10-18 15:40:14

标签: linq

如何在另一个.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 ..?

2 个答案:

答案 0 :(得分: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 });

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

答案 1 :(得分: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 }));