我有一个字典,salaryFitmentDictionary
我想根据例子查询(linq或lambda):where employeedId = 1
和EarningDeductionId = 145
并得到余额的值{{1} 1}}。
我将如何实现这一目标?
EDBalance
答案 0 :(得分:2)
IEnumerable<SalaryFitmentInfoMonth> salaries = salaryFitmentDictionary[1];
SalaryFitmentInfoMonth salary = salaries.FirstOrDefault(s => s.EDId == 45);
您应该处理salaryFitmentDictionary
不包含此ID的情况。因此,您可以使用TryGetValue
代替。如果没有工资,EDId
FirstOrDefault
将返回null。
所以这是更安全的版本:
IEnumerable<SalaryFitmentInfoMonth> salaries;
if(salaryFitmentDictionary.TryGetValue(1, out salaries))
{
SalaryFitmentInfoMonth salary = salaries.FirstOrDefault(s => s.EDId == 45);
if(salary != null)
{
// do something ...
}
}
如果您预计有多个匹配,则可以使用Enumerable.Where
代替FirstOrDefault
。
答案 1 :(得分:1)
您可以在LINQ方法语法中使用SelectMany方法:
Int32 id = 1;
Int32 edId = 147;
var result = salaryFitmentDictionary.
Where((pair) => pair.Key == id ).
SelectMany((pair) =>
pair.Value.Where((perEmployeeFitment) => perEmployeeFitment.EDId == edId)).
Select(perEmployeeFitment => perEmployeeFitment.EDBalance).
Single();
或者在查询语法中:
Int32 id = 1;
Int32 edId = 147;
var result = (from pair in salaryFitmentDictionary
from perEmployeeFitment in pair.Value
where pair.Key == id
where perEmployeeFitment.EDId == edId
select perEmployeeFitment.EDBalance).Single();