列表参考问题(LINQ疑似)

时间:2012-06-16 00:11:31

标签: c# linq

我有一个教学插槽的名单,我试图填补老师和越位人员(来自同一个名单)。
如果我直接执行该程序,尽管从不同的方法返回,所有教师和越位人员最终都会这样做 如果我暂停该计划,任何被观察创建的教师或越位将成为一名新的,不同的教师。 This问题似乎有一些相同的问题,这导致我怀疑我误解了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);

GetTeacher:

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列表返回。

1 个答案:

答案 0 :(得分:2)

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

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