简体   繁体   English

从LINQ查询语法转换为方法语法

[英]Translate from LINQ query syntax to method syntax

I have the following join: 我有以下加入:

var simpleJoin = from b in books
                 join p in publishers on b.PublisherName equals p.Name
                 where p.Id == 1
                 select b;

What is the equivalent using the method syntax? 使用方法语法的等效项是什么? I'm getting tripped up by the filter: 我被过滤器绊倒了:

simpleJoin = books.Join(publishers, p => p.PublisherName, b => b.Name, (b, p) => b).Where(*can't access publishers here*)

Can I not use books as my source collection? 我可以不使用books作为我的藏书吗? I'm wondering how we could manage filtering if we have multiple joins. 我想知道如果有多个联接,如何管理过滤。

You'll need to include both b and p in the resultSelector . 您需要在resultSelector同时包含bp For example, using an anonymous-typed object: 例如,使用匿名类型的对象:

simpleJoin = books.Join(publishers, p => p.PublisherName, b => b.Name, 
        (b, p) => new { b = b, p = p })
    .Where(result => result.p.Id == 1)
    .Select(result => result.b);

You can filter the publishers list prior to joining it to books : 您可以在将publishers列表加入books之前对其进行过滤:

var simpleJoin = books.Join(publishers.Where(p => p.Id == 1),
                             b => b.PublisherName, p => p.Name, (b, p) => b);

仅作为示例-您也可以不使用join子句:

books.Where(b => publishers.Exists(p => p.Name == b.PublisherName && p.Id == 1));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM