首页 > 解决方案 > 如何使用 C# linq 转换嵌套的 foreach 循环

问题描述

我有一个私有方法如下:

private Dictionary<string, decimal> GetRateByYear(IEnumerable<EmployerCu> cuList, 
    HashSet<long> activeCuSet, int year)
{
    Dictionary<string, decimal> cuDict = new Dictionary<string, decimal>();
    foreach (EmployerCu cu in cuList)
    {
        decimal rate = 0;    // rate maintains 0 if year is not match

        if (activeCuSet.Contains(cu.PayrollClassId))    // ignore inactive CUs
        {
            foreach (Rate r in cu.Rates)
            {
                if (r.Year == year)
                {
                    rate =  r.Value / Percentile;
                }
            }

            cuDict.Add(cu.Code.ToString(), rate);
        }        
    }

    return cuDict;
}

逻辑按预期工作。我只是想用 C# Linq 更多地挑战自己。我正在尝试使用“activeCuSet”过滤输入“cuList”,并在字典中添加 cu.code 和今年的汇率。

这是数据模型:

public class EmployerCu
{
    public long ClassId { get; set; }
    public long Code { get; set; }
    public string Name { get; set; }
    public long PayrollClassId { get; set; } 
    public Rate[] Rates { get; set; }
}

public class Rate
{
    public RateType Type { get; set; }
    public decimal Value { get; set; }
    public long Year { get; set; }
}

标签: c#linq

解决方案


说实话,并不是所有的东西都需要是Linq。有时它只会降低代码的可维护性和可读性。

然而,这可能是Linq解决方案使用的样子ToDictionary

从. Dictionary<TKey,TValue>_IEnumerable<T>

private Dictionary<string, decimal> GetRateByYear(IEnumerable<EmployerCu> cuList, HashSet<long> activeCuSet, int year)
  => cuList.Where(x => activeCuSet.Contains(x.PayrollClassId))
                .ToDictionary(
                    x => x.Code,
                    x => x.Rates.LastOrDefault(y => y.Year == year)?.Value / Percentile ?? 0);

注意:我使用LastOrDefault的是你的循环正在做的事情


推荐阅读