如何用LINQ通过指定Period获取BrancheBO中brancheRuleOverviews的条目列表
使用LINQ根据指定Period获取BrancheRuleOverviews条目列表
没问题,咱们来一步步实现你要的需求~首先得先解决一个小问题:你的BrancheBO里的brancheRuleOverviews是私有字段,外部代码直接访问不到它。所以第一步得先调整这个字段的访问权限,或者给它加一个公共的 getter 属性,这样LINQ才能正常读取数据。
第一步:调整BrancheBO的访问权限
把私有字段改成公共属性,或者保留私有字段但暴露公共访问入口,比如:
public class BrancheBO { /// <summary> /// Branche Rules per Period /// </summary> // 方案1:直接改成公共属性 public Dictionary<Period, IEnumerable<BrancheRuleOverview>> BrancheRuleOverviews { get; private set; } // 方案2:保留私有字段,通过只读属性暴露 // private Dictionary<Period, IEnumerable<BrancheRuleOverview>> brancheRuleOverviews; // public Dictionary<Period, IEnumerable<BrancheRuleOverview>> BrancheRuleOverviews => brancheRuleOverviews; }
第二步:用LINQ实现查询
假设你已经有了填充好数据的branchSettings实例,并且指定了目标Period(比如叫targetPeriod),可以用下面的LINQ语句获取所有匹配的规则条目:
基础版(确保所有BrancheBO都包含目标Period)
如果能确定每个BrancheBO的BrancheRuleOverviews里都有targetPeriod这个键,直接用下面的代码:
var targetPeriod = // 你的目标Period实例; var matchingRules = branchSettings.CompanyBranches.Values // 取出所有BrancheBO里对应目标Period的规则列表,然后平铺成一个集合 .SelectMany(bo => bo.BrancheRuleOverviews[targetPeriod]);
安全版(处理可能不存在目标Period的情况)
如果有些BrancheBO可能没有targetPeriod的键,为了避免抛出KeyNotFoundException,可以用TryGetValue来安全获取:
var targetPeriod = // 你的目标Period实例; var matchingRules = branchSettings.CompanyBranches.Values // 尝试获取每个BrancheBO里的目标规则,不存在则返回空序列 .Select(bo => { bo.BrancheRuleOverviews.TryGetValue(targetPeriod, out var rules); return rules ?? Enumerable.Empty<BrancheRuleOverview>(); }) // 平铺所有非空的规则列表 .SelectMany(rules => rules);
代码解释
CompanyBranches.Values:获取BranchSettings中所有的BrancheBO实例SelectMany:把多个IEnumerable<BrancheRuleOverview>合并成一个单一的集合,这样你就能直接拿到所有匹配目标Period的规则条目- 安全版里的
TryGetValue:避免因某个BrancheBO没有目标Period而引发异常,同时用空序列替代不存在的情况,保证查询的稳定性
内容的提问来源于stack exchange,提问作者ankur
相关产品推荐
相关产品推荐

