LINQ JOIN Child Collection

最后都变了- 提交于 2021-02-11 15:51:56

问题


I have a meetingRepository class that returns IEnumerable and an attendeeRepository class that returns IEnumerable<Attendee>

public class meetingRepository
{
    IEnumerable<Meeting> GetAll()
    {
        //return all Meetings
    }
}

public class attendeeRepository
{
    IEnumerable<Attendee>GetAll()
    {
        //return all Attendees
    }
}


public class Meeting
{
    public int Id { get; set; }
    public DateTime Date { get; set; }
    public string FilePath { get; set; }
    public int Duration { get; set; }

    public IEnumerable<Attendee> Attendees { get; set; }
}

public class Attendee
{
    public int Id { get; set; }
    public int MeetingId { get; set; }
    public string Name { get set;}
    public string Role { get; set; }
}

Im struggling to come up with the link statement that will join my IEnumerable<Meeting> object with my IEnumerable<Attendee> joining each Attendee in the Attendees property of the Meeting to its related Attendee object based on the Attendee.Id

Help appreciated

Edit

@Thomas the meetingRepository I have available does not load the Attendees, it is just a full list of all Meetings (I editted to include the Id property).
So, to clarify, my meetingRepository returns an IEnumerable of a partial Meeting object (no attendees)

Id
Date
Duration
FilePath 

and my attendeeRepository returns an IEnumerable of participants (editted to include MeetingId

Id
MeetingId
Name
Role

Edit

I came up with the folowing that seems to work fine

var meetingsFull = from m in meetings
                    join a in attendees
                    on m.Id equals a.MeetingId into ma
                    select new Meeting
                    {
                        Id=pc.Id, 
                        Date=pc.Date, 
                        Duration=pc.Duration, 
                        FilePath=pc.FilePath, 
                        Attendees=ma
                    };

回答1:


var attendees = attendeeRepository.GetAll();

foreach(var meeting in meetingRepository.GetAll())
{ 
    meeting.Attendees = attendees.Where(at=>at.MeetingId == meeting.Id);
}

This should do it. After these assignments your all meetings now have the attendees lists ready in them.



来源:https://stackoverflow.com/questions/23417913/linq-join-child-collection

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!