在另一个循环中以分页方式迭代列表

时间:2016-02-06 06:00:04

标签: c# arrays paging nested-lists

我有三个收藏品。首先是一系列日子。接下来,每天的时间跨度集合。这些时间跨度每天都相同。接下来,我有一系列会话。

有4天。有6个时间跨度。有30个会议。

我需要每天迭代,每天以相同的方式分配每天的所有时间跨度。但是,我需要按顺序将会话分配给时间块。例如,第1天获得所有6个时间跨度,但仅前6个会话,1-6。第2天获得相同的时间跨度,但接下来的6个会话,7-12。

如何在同一方法中执行此操作?

到目前为止,这是我所拥有的,但是我无法绕过分页迭代部分。

var timeSlots = TimeSlotDataAccess.GetItems(codeCampId);
var assignableSlotCount = timeSlots.Where(t => !t.SpanAllTracks);

// determine how many days the event lasts for
agenda.NumberOfDays = (int)(agenda.CodeCamp.EndDate - agenda.CodeCamp.BeginDate).TotalDays;

// iterate through each day
agenda.EventDays = new List<EventDayInfo>(agenda.NumberOfDays);

var dayCount = 0;
while (dayCount <= agenda.NumberOfDays)
{
    var eventDate = agenda.CodeCamp.BeginDate.AddDays(dayCount);

    var eventDay = new EventDayInfo()
    {
        Index = dayCount,
        Day = eventDate.Day,
        Month = eventDate.Month,
        Year = eventDate.Year,
        TimeStamp = eventDate
    };

    // iterate through each timeslot
    foreach (var timeSlot in timeSlots)
    {
        var slot = new AgendaTimeSlotInfo(timeSlot);

        // iterate through each session
        // first day gets the first set of assignableTimeSlotCount, then the next iteration gets the next set of that count, etc.
        slot.Sessions = SessionDataAccess.GetItemsByTimeSlotId(slot.TimeSlotId, codeCampId).ToList();

        // iterate through each speaker
        foreach (var session in slot.Sessions)
        {
            session.Speakers=SpeakerDataAccess.GetSpeakersForCollection(session.SessionId, codeCampId);
        }
    }

    agenda.EventDays.Add(eventDay);

    dayCount++;
}

1 个答案:

答案 0 :(得分:0)

我最终在基于GetItemsByTimeSlot()方法的新方法中使用LINQ。获取该集合的匹配子集的新签名和示例如下所示。

以下是我如何称呼它:

slot.Sessions = SessionDataAccess.GetItemsByTimeSlotIdByPage(slot.TimeSlotId, 
codeCampId, dayCount + 1, timeSlotCount).ToList();

这是它的样子:

public IEnumerable<SessionInfo> GetItemsByTimeSlotIdByPage(int timeSlotId, int codeCampId, int pageNumber, int pageSize)
{
    var items = repo.GetItems(codeCampId).Where(t => t.TimeSlotId == timeSlotId);

    items.Select(s => { s.RegistrantCount = GetRegistrantCount(s.SessionId); return s; });

    // this is the important part
    var resultSet = items.Skip(pageSize * (pageNumber - 1)).Take(pageSize);

    foreach (var item in resultSet)
    {
        item.Speakers = speakerRepo.GetSpeakersForCollection(item.SessionId, item.CodeCampId);
    }

    return resultSet;
}