[英]how to turn nested foreach loop with C# linq
我有一个私有方法如下:
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 。 有时它只会降低代码的可维护性和可读性。
然而,这可能是使用ToDictionary
的Linq解决方案的样子
从
IEnumerable<T>
创建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
因为那是您的循环所做的
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.