我有一个日期时间值的通用列表:weekADates
我有一个TimeTable实体的通用列表: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?
答案 0 :(得分: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
});
编辑:修复了第三个从字典中获取值,而不是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
})));