0

我有一个教学名册,我试图用老师和越位者(来自同一个列表)来填补。
如果我直接运行程序,所有的 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 列表返回。

4

1 回答 1

2

问题很可能是您Random在每次调用中都创建了一个新实例。如果您快速调用它,则 Random 实例都将使用相同的种子播种,并在每次调用时返回相同的值。

我建议将Random实例移动到类级别变量中,这将导致它被构造一次,并在您连续多次调用此方法时提供更多“随机”值。

于 2012-06-16T00:29:36.527 回答