从多个条件的同一张表进行Linq查询

时间:2018-07-05 06:46:12

标签: c# entity-framework linq linq-to-sql

我正在尝试的当前查询是

 public async Task<ActionStatus<IList<SelectedListViewModel>>> GetProjectMembersByClient(Guid clientId)
    {
var userProjects = _unitofwork.UserProjects;
        var ProjectIds = userProjects.Get(filter: x => x.UserId == clientId).Select(y=> new UserProjects {UserId=y.UserId,ProjectId=y.ProjectId });
}

我的表格格式为(表格名称:“ UserProject”)

MapId projectId UserID
1      123       89
2      123       69
3      123       36

我想在传递用户ID时获得所有包含相同项目ID的所有用户ID。

例如:如果我的参数是89(对应的projectid是123),我希望获得69和36作为新的“ UserProjects”模型。

注意:userid可能有多个projectid,在这种情况下,还希望从所选projectid的所有成员中获取

2 个答案:

答案 0 :(得分:2)

您可以通过下面的Linq获取此类数据集。

var userIds = userProjects
    .GroupBy(m => m.ProjectId)
    .Where(g => g.Any(m => m.UserId == userId))
    .SelectMany(g => g.Select(m => m.UserId))
    .Distinct();

这将产生与位的解决方案+ Distinct()相同的结果。但是,我想知道它们在运行时会有多少不同。因此,我只是将两种代码的处理时间与10,000条记录的数据(每次随机生成)进行了100次比较。结果是我的上述解决方案速度提高了约1.5倍(或更多)。这是macOS 10.13.5上单声道5.10.1.57的结果。如果性能对您很重要,请在您的环境中尝试。

答案 1 :(得分:1)

忽略拼写错误,并假设userIdclientId是数字。 首先获取您需要的projectIds

var projectIds = _unitofwork.UserProjects.Where(p=>p.UserId==clientId).Select(p=>p.ProjectId);

,然后获取与那些projectIds关联的用户ID;像这样的东西:

var userIds = _unitofwork.UserProjects.Where(p=>projectIds.Contains(p.ProjectId)).Select(p=>p.UserId);
相关问题