如何正确配置foreach循环以避免索引超出范围错误?

时间:2016-04-09 04:10:00

标签: c# .net arrays linq foreach

我有一个对象:

 public List<double> obj { get; set; }

public class Employee
{
     public int EmployeeId { get; set; }
     public int Skillssetpoints { get; set; }
     public string Name { get; set; }
     public Nullable<System.DateTime> Date { get; set; }
}

记录是这样的:

EmployeeId   SkillssetPoints   Date
 1              5             4/5/2016 16:12:12
 2              12             3/5/2016 17:12:12
 3              4              8/5/2016 8:12:12
 4              20             1/5/2016 2:12:12

这个obj会像这样包含价值:

"obj":[10,20]

现在我想要做的是我将获得所有员工数据,并且对于每个员工数据,我将执行乘法运算 像这样:

1st records:obj[0] * Skillssetpoints  (10*5=50)
2nd records:obj[0] * Skillssetpoints  (20*12=240)

这是我的循环:

var employeeList=context.Employee.ToList();

  foreach (var item in employeeList.Select((value, index) => new { value, index }))
  {
          var employee = new Employee();
          employee.Skillssetpoints=obj[item.index] * item.Skillssetpoints;
          //Save records in database
  }

但是这里的问题是我为员工获得4条记录,而我的obj包含2个值,因此低于错误:

错误:索引超出范围。必须是非负数且小于集合的大小。

注意:我还想考虑当我的员工记录少于列表对象中的项目时的情况。

如何正确配置此循环?

2 个答案:

答案 0 :(得分:2)

您可以使用Enumerable.Take()根据n中的项目数仅处理第一个obj项:

foreach (employeeList.Take(obj.Count).Select((value, index) => new { value, index }))
{
    .....
}

如果obj中的项目数量超过employeeList中的项目数量,这也应该适用。在这种情况下,只会处理与employeeList一样多的数据。

答案 1 :(得分:1)

仅当Value中有效obj时才计算技能点。

foreach (var item in employeeList.Select((value, index) => new { value, index }))
{
      var employee = new Employee();
      if(item.index >= 0) // Calculate Skill points only when value is avialable.
         employee.Skillssetpoints=obj[item.index] * item.Skillssetpoints;
      //Save records in database
}

如果您想忽略插入空记录,可以在循环内调用break

foreach (var item in employeeList.Select((value, index) => new { value, index }))
{
      var employee = new Employee();
      if(item.index < 0) break;

      employee.Skillssetpoints=obj[item.index] * item.Skillssetpoints;
      //Save records in database
}
相关问题