InvalidOperationException: Sequence contains more than one element

此生再无相见时 提交于 2019-12-30 08:37:07

问题


I have the following code below for a payroll program. The first dictionary holds the employee IDs and corresponding basic pays held in a master data table. The second dictionary holds the employee IDs and corresponding basic pays held in a salary fitment table - used for processing. I want to update the salary fitment basic pays for each employee ID that do not match in the master table. (Changes in salary).

var OHEMDictionary = employees.OrderBy(es => es.empID)
                     .ToDictionary(od => od.empID,
                     od => od.salary);

var SalaryFitmentDictionary = salaryFitments
                              .Where(x => x.U_PD_Code.Trim().ToString() == "SYS001")
                              .OrderBy(es => es.U_Employee_ID)
                              .ToDictionary(od => od.U_Employee_ID,
                                            od => od.U_PD_Amount);

var difference = OHEMDictionary
                .Where(kv => SalaryFitmentDictionary[kv.Key] != kv.Value);

difference.ToList().ForEach(x =>
                    {
                        decimal salary = x.Value.Value;

                        var codeToUpdate = salaryFitments
                                        .Where(y => y.U_Employee_ID.Equals(x.Key))
                                        .Select(z => z.Code)
                                        .SingleOrDefault(); `**<---exception thrown here**`

                        var salaryFitment = salaryFitmentService
                                            .GetSalaryFitment(codeToUpdate);

                        if (salaryFitment != null)
                        {
                            // Save record
                            salaryFitmentService
                           .UpdateSalaryFitment(salaryFitment, salary.ToString());
                        }
                    });

However, I keep getting the error 'Sequence contains more than one element'. How do I solve this error?


回答1:


You can use FirstOrDefault() but SingleOrDefault throws an exception if more than one element exists.

Here you can see exactly what the single or default method does: http://msdn.microsoft.com/en-us/library/system.linq.enumerable.singleordefault(v=vs.100).aspx



来源:https://stackoverflow.com/questions/15021257/invalidoperationexception-sequence-contains-more-than-one-element

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!