简体   繁体   English

如何将此Linq查询语法转换为方法语法?

[英]How to convert this Linq query syntax to method syntax?

The answer here contained the following query: 这里答案包含以下查询:

var query = from role in _db.Roles
            where role.Name == roleName
            from userRoles in role.Users
            join user in _db.Users
            on userRoles.UserId equals user.Id
            select user;

How would I reproduce the same query using Linq method syntax? 如何使用Linq方法语法重现相同的查询?

var query = _db.Roles
    .Where(role => role.Name == roleName)
    .SelectMany(role => role.Users)
    .Join(_db.Users, userRole => userRole.UserId, user => user.Id, (role, user) => user);

Some explanation 一些解释

var query = from role in _db.Roles
        where role.Name == roleName // this will be translated to .Where
        from userRoles in role.Users // this is .SelectMany
        join user in _db.Users // this is .Join
        on userRoles.UserId equals user.Id // second and third arguments of .Join
        select user; // last argument of .Join

This is the method syntax version 这是方法语法版本

    var query =
        _db.Roles.Where(role => role.Name == roleName)
            .SelectMany(role => role.Users, (role, userRoles) => new {role, userRoles})
            .Join(_db.Users, @t => userRoles.UserId, user => user.Id, (@t, user) => user);

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

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