InvalidOperationException异常:序列包含一个以上的元件 [英] InvalidOperationException: Sequence contains more than one element

查看:3421
本文介绍了InvalidOperationException异常:序列包含一个以上的元件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有下面的下面的代码为工资计算程序。
第一字典拥有员工ID和相应的基本自付在主数据表中。
第二辞典拥有员工ID和相应的基本自付在工资表装修举行 - 用于处理。
我想更新的薪水装修基本支付不中主表匹配每个员工ID。 (工资的变化)

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?

推荐答案

您可以使用FirstOrDefault(),但如果多个元素存在的SingleOrDefault抛出异常。

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

在这里你可以看到什么单一的或默认的方法做:
http://msdn.microsoft.com/en-us/library/system.linq.enumerable.singleordefault(v=vs.100 )的.aspx

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

这篇关于InvalidOperationException异常:序列包含一个以上的元件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆