簡體   English   中英

如何正確配置foreach循環以避免索引超出范圍錯誤?

[英]How to configure foreach loop properly to avoid index out of range error?

我有一個對象:

 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個值,因此得到以下錯誤:

錯誤:索引超出范圍。 必須是非負數且小於集合的大小。

注意 :我還想考慮當我的員工記錄少於列表對象中的項目時的情況。

如何正確配置這個循環?

您可以使用Enumerable.Take()根據obj的項目數僅處理前n項目:

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

這也應該適用於obj中的項目數量多於employeeList 在這種情況下,只處理與employeeList一樣多的數據。

計算技能點只有當你有有效的Valueobj

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 inside循環。

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
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM