从字典值中获取项目列表

时间:2018-01-09 11:41:00

标签: c# linq

我在课程中有一个属性

Public class BranchSettings
{
     public Dictionary<Period, BrancheBO> CompanyBranches;
}

BranchBo看起来像这样

public class BrancheBO
    {
        /// <summary>
        /// Branche Rules per Period
        /// </summary>
        private Dictionary<Period, IEnumerable<BrancheRuleOverview>> brancheRuleOverviews;

}

我想通过使用linq

提供句点来访问此brancheRuleOverviews
Var branchSettings = GetSettings(id);//this is being returned by external provider.

所以branchSettings对象填充了CompanyBranches。我可以对它进行循环,有没有办法使用Linq。

3 个答案:

答案 0 :(得分:0)

我不确定我是否正确,但以下内容可以帮助您:

var brancheRuleOverviews = branchSettings.SelectMany(i => i.CompanyBranches.Values)
                               .Where(i => i.brancheRuleOverviews.ContainsKey(period))
                               .SelectMany(i => i.brancheRuleOverviews[period]);

这将为您提供所有BrancheRuleOverview的列表,其中“第二级”Period等于period,但忽略第一级的句点并假设内部词典不是私有的

答案 1 :(得分:0)

我猜branchSettingsBranchSettings的一个实例。没有LINQ需要访问该值:

Period searchThisPeriod = ...
IEnumerable<BrancheRuleOverview> desiredResult = Enumerable.Empty<BrancheRuleOverview>();
if(settings.CompanyBranches.ContainsKey(searchThisPeriod))
{
    desiredResult = settings.CompanyBranches[searchThisPeriod].brancheRuleOverviews[searchThisPeriod];
}

有点奇怪,你需要两个带有相同键的词典。另一件事,你的内部字典是私人的,所以你不能以这种方式访问​​它。将其公开或使用属性/方法来访问该值。

请注意,Period需要覆盖EqualsGetHashCode,否则您应该实现用于初始化词典的自定义IEqualityComparer<Period>

答案 2 :(得分:0)

对各种类的结构和成员的可访问性做出一些假设 - 即BrancheRuleOverviews需要公开

using System.Collections.Generic;
using System.Linq;

namespace ConsoleApp1
{
    class Program
    {
        static void Main(string[] args)
        {
            var branchSettings = new BranchSettings();
            var branchOverviews = from bs in branchSettings.CompanyBranches
                from bro in bs.Value.BrancheRuleOverviews
                where bro.Key.PeriodName.Equals(int.Parse(args[0]))
                select bro;
        }
    }


    public class BranchSettings
    {
        public Dictionary<Period, BrancheBO> CompanyBranches;
    }


    public class BrancheBO
    {
        /// <summary>
        /// Branche Rules per Period
        /// </summary>
        public Dictionary<Period, IEnumerable<BrancheRuleOverview>> BrancheRuleOverviews;
    }

    public class Period
    {
        public int PeriodName;
    }

    public class BrancheRuleOverview
    {
    }
}