C# 是否可以将两个linq查询合并为一个?

C# 是否可以将两个linq查询合并为一个?,c#,asp.net,entity-framework,linq,C#,Asp.net,Entity Framework,Linq,我的数据库中有一个表(用户),如下所示(带有示例数据的表结构): 每个用户都有一个唯一的IdUser,而多个用户可以拥有相同的IdLicense。我想在一个查询列表中仅使用IdUser选择具有相同IdLicense的所有用户。我使用两个linq查询来实现这一点: //Get logged user IdUser var claims = User.Identities.FirstOrDefault()?.Claims.FirstOrDefault()?.Value; //Get log

我的数据库中有一个表(用户),如下所示(带有示例数据的表结构):

每个用户都有一个唯一的IdUser,而多个用户可以拥有相同的IdLicense。我想在一个查询列表中仅使用IdUser选择具有相同IdLicense的所有用户。我使用两个linq查询来实现这一点:

 //Get logged user IdUser
 var claims = User.Identities.FirstOrDefault()?.Claims.FirstOrDefault()?.Value;

 //Get logged user IdLicense
 var license = _context.User.Where(x => x.IdUser == new Guid(claims))
               .Select(x => x.IdLicense).FirstOrDefault();

 //Get users with this license
 var users = _context.User.Where(x => x.IdLicense == license).ToList();


仅使用一个linq查询就可以获得具有此许可证的相同用户列表?

一个解决方案可以是:

var userId = new Guid(claims);
var users = (from user in _context.Users
            let licenseId = _context.User.Where(x => x.IdUser == userId)
               .Select(x => x.IdLicense).FirstOrDefault();
            where user.IdLicense == licenseId).ToList();

一种解决办法是:

var userId = new Guid(claims);
var users = (from user in _context.Users
            let licenseId = _context.User.Where(x => x.IdUser == userId)
               .Select(x => x.IdLicense).FirstOrDefault();
            where user.IdLicense == licenseId).ToList();

这一个应该工作得很快:

var userId=新Guid(声明);
变量查询=
来自ul in_context.Users
其中ul.IdUser==userId
在ul.IdLicense上加入u_context.Users等于u.IdLicense
选择u;
var users=query.ToList();

这一个应该工作得很快:

var userId=新Guid(声明);
变量查询=
来自ul in_context.Users
其中ul.IdUser==userId
在ul.IdLicense上加入u_context.Users等于u.IdLicense
选择u;
var users=query.ToList();

我稍微调整了您的代码(在查询结束时没有选择),效果非常好。谢谢,我已经稍微调整了你的代码(在查询结束时没有选择),它工作得非常完美。谢谢我检查过了,你的代码在五次尝试中平均为65毫秒,Mohsen Esmailpour代码平均为75.6毫秒。非常感谢您的建议:)我的问题代码达到avarage 158无任何特殊之处,其他答案引入了外部应用,这不是很快的操作,在这种情况下也不需要。我检查过,您五次尝试的代码平均65毫秒,Mohsen Esmailpour代码平均75.6毫秒。非常感谢您的建议:)我的问题代码达到avarage 158没有什么特别的,其他答案介绍了外部应用,这不是那么快的操作,在这种情况下不需要。