如何使用C#linq转换嵌套的foreach循环

如何使用C#linq转换嵌套的foreach循环,c#,linq,C#,Linq,我有一个私有方法,如下所示: private Dictionary<string, decimal> GetRateByYear(IEnumerable<EmployerCu> cuList, HashSet<long> activeCuSet, int year) { Dictionary<string, decimal> cuDict = new Dictionary<string, decimal>();

我有一个私有方法,如下所示:

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;
}

说实话,并不是每件事都需要灵巧。有时,它只会降低代码的可维护性和可读性

然而,这可能是Linq解决方案使用

IEnumerable
创建
字典

私人词典GetRateByYear(IEnumerable cuList,HashSet-activeCuSet,int-year)
=>cuList.Where(x=>activeCuSet.Contains(x.PayrollClassId))
.ToDictionary(
x=>x.代码,
x=>x.Rates.LastOrDefault(y=>y.Year==Year)?。值/百分位数??0;

注意:我使用了
LastOrDefault
,因为你的循环就是这么做的

@Jawad我对Linq很陌生。我对语法很感兴趣,为了可读性,我试着总结一下什么时候使用它,什么时候不使用它的规则。@Terence很可能没有,在某个点上,有些东西在循环。有一个真正的机会,它的性能较差
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; }
}
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);