如何从Dictionary <int,ienumerable <struct =“”>&gt; </int,>中查找值

时间:2014-08-22 11:00:44

标签: c# linq dictionary lambda

我有一个字典,salaryFitmentDictionary我想根据例子查询(linq或lambda):where employeedId = 1EarningDeductionId = 145并得到余额的值{{1} 1}}。

我将如何实现这一目标?

EDBalance

2 个答案:

答案 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();