即使未引用先前的值,也会通过每个循环迭代覆盖值

时间:2017-02-28 15:51:22

标签: c# entity-framework loops

我需要一些帮助来调试我的代码块来获取程序。

这是块:

    foreach (var job in socs)
    {
        string educationNeeded = "";
        string experienceNeeded = "";
        if (job.soc.EducationNeeded != null)
        {
            educationNeeded = job.soc.EducationNeeded.Education;
            experienceNeeded = job.soc.EducationNeeded.WorkExperience;
        }
        // For every onetsoc and every cipOnetSoc for each onetsoc, find the programs that apply and add them to the OccupationModel
        foreach (var onetSoc in job.soc.OnetSocs.ToList())
        {
            if (onetSoc != null)
            {
                var occupation = new OccupationModel()
                {
                    BrightFutureScore = new Random().Next(1, 100),
                    Description = onetSoc.Description,
                    PercentChange = job.percentChange,
                    EducationRequirement = educationNeeded,
                    ExperienceNeeded = experienceNeeded,
                    OpenPositions = job.averageAnnualOpenings ?? 0,
                    StartingSalary = job.annualWageMedian,
                    Name = onetSoc.Name,
                    OnetSoc = onetSoc.OnetSoc1
                };
                var cipOnetSocs = onetSoc.CipOnetSoc.ToList();
                if (cipOnetSocs.Count > 0)
                {
                    var cipOnetSocsCips = cipOnetSocs.Select(x => x.Cip6).ToList();
                    var programs = collegePrograms
                        .Where(x => cipOnetSocsCips.Contains(x.Cip))
                        .ToList();
                    foreach(var x in programs)
                    {
                        x.OnetSoc = onetSoc.OnetSoc1;
                    };
                    if (programs.Count > 0)
                    {
                        occupation.Programs = programs;
                    }
                }
                occupations.Add(occupation);
            }
        }

    }

如果你看一下foreach(var x in programs)循环,那么正在做的是为每个soc中的每个onetsoc中的每个程序设置OnetSoc,如果这是有意义的话。这就是三个循环的作用:

  1. 遍历每个soc

  2. 遍历该soc上的每个OnetSoc并创建OccupationModel并获取cipOnetSocs的程序

  3. 遍历每个程序,将其OnetSoc值设置为第二级循环的值

  4. 我得到的行为是,不知何故,在调试过程中,onetSoc是正确的,但是当我们遍历每个soc时,先前添加的职业的onetSoc值会发生变化。 我在循环中遗漏了可能导致此问题的内容吗?

0 个答案:

没有答案