Linq从嵌套列表中找到所有具有ID

时间:2019-03-18 13:01:59

标签: c# .net list linq core

我有以下课程:

public class AssignmentDetails : EntityBase
    {
        public DateTime StartingTime { get; protected set; }
        public DateTime EndingTime { get; protected set; }
        public ICollection<AssignedUser> AssignedUsers { get; protected set;}
        public Assignment Assigment { get; protected set; }
        public int AssigmentId { get; protected set; }
        public int OwnerId { get; protected set; }
        public User Owner { get; protected set; }
        public State State { get; protected set; }
        public AssignmentDetails(DateTime startingTime,DateTime endingTime,int ownerId,State state,ICollection<AssignedUser> assignedUsers)
        {
            AssignedUsers = assignedUsers;
            StartingTime = startingTime;
            EndingTime = endingTime;
            OwnerId = ownerId;
            State = state;
        }
        public AssignmentDetails() { }
    }

 public class Assignment : EntityBase
    {
        public string Title { get; protected set; }
        public AssignmentDetails AssignmentDetails { get; protected set; }
        public string Description { get; protected set; }
        public int ParentAssignmentId { get; protected set; }
        public Assignment(string title,string description,AssignmentDetails assignmentDetails)
        {
            Title = title;
            Description = description;
            AssignmentDetails = assignmentDetails;
        }
        public void AddParentAssignment(int parentAssignmentId)
        {
            ParentAssignmentId = parentAssignmentId;
        }
        public Assignment(){ }
    }

 public class AssignedUser : EntityBase
    {
        public AssignmentDetails Assignment { get; protected set; }
        public int AssignmentDetailsId { get; protected set; }
        public int UserId { get; protected set; }
        public AssignedUser(int userId)
        {
            UserId = userId;
        }
        public AssignedUser() { }
    }

我需要找到特定用户的所有分配,该用户是分配的所有者,或者是在AssignedUsers中分配的

我尝试了以下方法和其他一些替代方法,但看起来好像在某个地方引起了我的注意。

public async Task<List<Assignment>> GetAllAsignmentsAsync(int userId)
    {
        return await _context.Assignments
            .Include(a => a.AssignmentDetails)
            .Where(x => x.AssignmentDetails.OwnerId == userId || x.AssignmentDetails.AssignedUsers.SelectMany(u=> u.UserId== userId))
            .ToListAsync();
    }

1 个答案:

答案 0 :(得分:5)

    .Where(x => x.AssignmentDetails.OwnerId == userId 
|| x.AssignmentDetails.AssignedUsers.Any(u=> u.UserId== userId))

使用Any返回truefalse条件。 SelectMany根据条件选择一些对象