我有一个教学名册,我试图用老师和越位者(来自同一个列表)来填补。
如果我直接运行程序,所有的 Teachers 和 Offsiders 最终都一样,尽管它们是从不同的方法返回的。
如果我暂停程序,任何被观察到的教师或越位者都将成为新的、不同的教师。
这个问题似乎有一些相同的内容,这导致我怀疑我误解了 linq 的一个重要部分,以及查询何时完成,但我不明白即使跨 2 个函数也会发生这种情况。
调用代码以及 2 个函数如下所示。我很感激你能提供的任何见解。
调用代码:
Teacher T = list.GetTeacher(lesson);
lesson.SetTeacher(T);
lesson.Teacher.AddLesson(lesson);
Teacher O = list.GetOffsider(lesson);
lesson.SetOffsider(O);
lesson.Offsider.AddLesson(lesson);
获取老师:
public Teacher GetTeacher(Lesson lesson)
{
List<Teacher> Eligible = Teachers.Where(t1 => t1.Active && t1.Styles.Any(ts1 => ts1.Style == lesson.Style.Style && ts1.Level >= lesson.Style.Level)).ToList();
if (Eligible.Count == 0)
throw new ArgumentException("Don't have any teachers for that style and/or level");
List<Teacher> HaventTaught = Eligible.Where(t => !t.DatesTaught.Any(dt => dt.AddDays(21).Day < DateTime.Now.Day)).ToList();
if (HaventTaught.Count == 0)
{
Random r = new Random();
return Eligible[r.Next(Eligible.Count)];
}
else
{
Random r = new Random();
return HaventTaught[r.Next(HaventTaught.Count)];
}
}
GetOffsider:
public Teacher GetOffsider(Lesson lesson)
{
if (lesson.Teacher == null)
{
throw new ArgumentNullException("Must assign a Teacher to a lesson before an Offsider");
}
List<Teacher> Eligible = Teachers.Where(t2 => t2.Active && t2.Styles.Any(ts2 => ts2.Style == lesson.Style.Style && ts2.Level >= lesson.Style.Level)).ToList();
//remove conflicts of interest
Eligible = Eligible.Where(t3 => !t3.Avoid.Any(n2 => n2.Equals(lesson.Teacher.Name)) && !lesson.Teacher.Avoid.Any(n4 => n4.Equals(t3.Name))).ToList();
if (Eligible.Count == 0)
throw new ArgumentException("Don't have any offsiders for that style and/or level");
List<Teacher> HaventTaught = Eligible.Where(t4 => !t4.DatesTaught.Any(dt2 => dt2.AddDays(21).Day < DateTime.Now.Day)).ToList();
if (HaventTaught.Count == 0)
{
Random r = new Random();
return Eligible[r.Next(Eligible.Count)];
}
else
{
Random r = new Random();
return HaventTaught[r.Next(HaventTaught.Count)];
}
}
注意:这两个函数当前都从 HaventTaught 列表返回。