1

我有一个日期时间值的通用列表:weekADates

我有一个时间表实体的通用列表: response.TimeTableWeek

public class TimeTable
{
    public int LessonNumber { get; set; }

    /// <summary>
    /// For each day and lessonnumber in the week there is a schooclass code assigned
    /// </summary>
    public IDictionary<DayOfWeek,string> WeeklySchoolclassCodes { get; set; }
}

这段代码需要改成 LINQ 查询:

var periodList = new List<Period>();
foreach (DateTime date in weekADates)
{
    foreach (TimeTable timetable in response.TimeTableWeek)
    {
        for (int i = 0; i < timetable.WeeklySchoolclassCodes.Count; i++)
        {
            var p = new Period();
            p.LessonNumber = timetable.LessonNumber + 1;
            p.LessonDate = date;
            p.SchoolclassCode = timetable.WeeklySchoolclassCodes[date.DayOfWeek];
            periodList.Add(p);
        }
    }
}

我尝试了 .Select 和 .SelectMany 的许多变体,但我找不到解决方案。

这就是周期列表的样子。

在此处输入图像描述

您如何将其更改为 linq?

4

1 回答 1

3

试试这个

periodList.AddRange(
    from date in weekADates
    from timetable in response.TimeTableWeek
    from schoolclassCode in timetable.WeeklySchoolclassCodes.Values
    select new Period
    {
        LessonNumber = timetable.LessonNumber + 1,
        LessonDate = date,
        SchoolclassCode = schoolclasscode
    });

编辑:修复了第三个 from 以从字典中获取值,而不是 KeyValuePairs。

在方法风格中,你可以这样写:

periodList.AddRange(
    weekADates.SelectMany(date => 
    response.TimeTableWeek.SelectMany(timetable =>
    timetable.WeeklySchoolclassCodes.Values.Select(schoolclassCode =>
    new Period
    {
        LessonNumber = timetable.LessonNumber + 1,
        LessonDate = date,
        SchoolclassCode = schoolclasscode
    })));
于 2013-02-19T21:49:40.903 回答