LINQ复合选择问题

5

我在尝试编译一个LINQ复合选择语句时遇到了问题。以下是代码:

int[] numbersA = { 0, 2, 4, 5, 6, 8, 9 };
int[] numbersB = { 1, 3, 5, 7, 8 };

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

这段代码来自于这里的教程,在“SelectMany - Compound from 1”标题下:http://msdn.microsoft.com/en-us/vcsharp/aa336758.aspx#SelectSimple1。我收到的编译时错误如下所示:“一个查询体必须以select子句或group子句结尾”。逗号紧随在“numbersA”之后,这就是产生错误的地方。现在我无法弄清楚我的错误在哪里,因为这只是照着微软网站上的代码写的。非常感谢您的帮助。

谢谢你恰好问我这一分钟打算问的问题 :) - mafu
3个回答

12

你的代码不是一个有效的LINQ表达式。from从句仅支持单个集合。你应该重复整个from从句。你可能意思是这样:

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

你先到了这里 :) 我给你点赞。 - Charlie Flowers
1
谢谢,我尝试了一下,效果很棒。遗憾的是 MS 网站有无效代码! - Chris

10

仅供参考,使用SelectMany的等效流畅语法:

var pair = numbersA.SelectMany(a => numbersB, (a, b) => new {a, b})
                   .Where(n => n.a < n.b);

3
如果我理解您的意图正确,那么您需要另一个表单。
就像这样:
var pairs =
    from a in numbersA // Comma removed from end of line here
    from b in numbersB // additional "from" keyword at start of line
    where a < b
    select new {a, b};

好的,谢谢!不过很抱歉,Mehrdad已经先回答了。 - Chris

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接