[英]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
一樣多的數據。
計算技能點只有當你有有效的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
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.