c# - 如何使用 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; }
}
解决方案
说实话,并不是所有的东西都需要是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
的是你的循环正在做的事情
推荐阅读
- jekyll - Jekyll:如何在 html 转义 code-snippet.html 时 {% include code-snippet.html %}
- python - 噪声模块中的 pnoise2() 函数产生 SegFault python 3.8
- node.js - MongoDB 聚合使用 NodeJS 返回空数组
- random - SOAPUI Groovy UI 从加载列表中选择一个随机值
- angular - 获取 Angular 10 中任意 url 的路由信息
- html - 为什么我的 django 个人资料更新功能不起作用?
- python - 两个数据帧的组合 - 仍然显示 NaN 值
- swift - 如何在 swift 对象上按字段检查相等性
- kotlin - 协程中的异常处理和取消
- azure-devops - 减少 git checkout 时间?