【问题标题】:Linq SelectMany errorLinq SelectMany 错误
【发布时间】:2015-03-13 19:17:29
【问题描述】:

我是 LINQ lambda 表达式的新手,关于以下问题我已经被困了一段时间。 我想执行左外连接并想选择左表而不是右表,但是当我选择左表时,下面的查询给了我错误

“查询”是 IQueryable,也是“model2”

 var model = query.GroupJoin(model2,
                    o => o.plu,
                    m => m.plu,
                    (o, m) => new
                    {
                        SmartCoupon = o,
                        Product = m.DefaultIfEmpty(),
                    })
                    .SelectMany
                    (
                        a => a.SmartCoupon
                    );

下面是右表的正确查询,但我需要左表

var model = query.GroupJoin(model2,
                    o => o.plu,
                    m => m.plu,
                    (o, m) => new
                    {
                        SmartCoupon = o,
                        Product = m.DefaultIfEmpty(),
                    })
                    .SelectMany
                    (
                        a => a.Product 
                    );

【问题讨论】:

    标签: c# linq lambda


    【解决方案1】:

    你误会SelectMany()。

    它用于在您需要Select()这里的另一个列表中展平列表:

    .Select(a => a.SmartCoupon);
    

    假设你有List<List<string>>`` and you want all string in aList, then you need to useSelectMany()`。

    例如:

    var nameList = new List<List<string>>()
                                {
                                    new List<string>
                                        {
                                           "Matt","Adam","John","Peter","Owen"
                                        },
                                    new List<string>
                                        { 
                                           "Tim","Jim","Andy","Fred","Todd"
                                        }
                                };
    

    现在使用SelectMany() 得到一个IEnumerable&lt;string&gt;,如果你使用Select 它将返回IEnumerable&lt;IEnumerable&lt;string&gt;&gt;:

    var namesInSingleList = nameList.SelectMany(x => x);
    

    你可以看到difference between Select and SelectMany in this SO post

    【讨论】:

    • 好的。但是如果我替换选择我会有左加入吗?因为我在 sql pro filer 中查看了输出 sql 查询,并且输出查询中没有与产品表的左外连接
    • Select 和 SelectMany 与左连接无关
    • 好吧,我想合并 selectmany 中的两个表记录并将它们作为一个列表返回。像这样交叉加入stackoverflow.com/a/13035259/1202610
    • 试图理解。工作我现在被困在这个问题上太久了。等待。我们可以在stackoverflow上聊天吗?请
    • 好吧,当我这样做的时候这个 var model = query.GroupJoin(model2, o => o.plu, m => m.plu, (o, m) => new { SmartCoupon = o, Product = m.DefaultIfEmpty() });我在查询“select * from (select * from SmartCoupon left join Product)”中得到这个结果,这是正确的,但我无法获取最外层选择语句的记录
    猜你喜欢
    • 1970-01-01
    • 2013-11-24
    • 1970-01-01
    • 1970-01-01
    • 2013-05-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多