【问题标题】:How to retrieve any keys in dictionary of composite values by a single value [closed]如何通过单个值检索复合值字典中的任何键[关闭]
【发布时间】:2020-11-23 19:08:46
【问题描述】:

我正在编写一个程序,该程序将打印关于内燃机部件发生情况的输出。我有一个名为 CarSystemParts 的抽象类,所有汽车零件类都继承自该类。

我有一个Dictionary<CarSystemPart, List<CarSystemPart>>,它显示了哪些类应该受到其他部分的影响或物理推动。它是这样定义的:

        PushCycle = new Dictionary<CarSystemPart, List<CarSystemPart>>()
        {
            { Accelerator, new List<CarSystemPart> { Carburetor } },
            { AirCleaner, new List<CarSystemPart> { } },
            { Alternator, new List<CarSystemPart> { Battery } },
            { Battery, new List<CarSystemPart> {  } },
            { CamShaft, new List<CarSystemPart> { FuelPump, Distributor, ValveExhaust, ValveIntake } },
            { Carburetor, new List<CarSystemPart> { ValveIntake } },
            { Crankshaft, new List<CarSystemPart> { Alternator, TimingChain, Pistons } },
            { Distributor, new List<CarSystemPart> { SparkPlugs } },
            { Flywheel, new List<CarSystemPart> { Crankshaft } },
            { FuelPump, new List<CarSystemPart> { Carburetor } },
            { FuelTank, new List<CarSystemPart> {  } },
            { IgnitionCoil, new List<CarSystemPart> { Distributor } },
            { IgnitionSwitch, new List<CarSystemPart> { IgnitionCoil, StarterMotor } },
            { Pistons, new List<CarSystemPart> { Crankshaft } },
            { SparkPlugs, new List<CarSystemPart> { Pistons } },
            { StarterMotor, new List<CarSystemPart> { Flywheel } },
            { TimingChain, new List<CarSystemPart> { CamShaft } },
            { ValveExhaust, new List<CarSystemPart> {  } },
            { ValveIntake, new List<CarSystemPart> { Pistons } } 
        };

例如曲轴操作AlternatorTimingChainPistons

但是,在几个 CarSystemPart 子类定义中,我需要知道该部件受到哪些部件的影响。

为了解决这个问题,我想生成一个List&lt;CarSystemPart&gt;,其中包含字典中的每个Key,其Values 在其列表中包含CarSystemPart

我发现我可以在 LINQ 中使用 FirstOrDefault 查找单个值来查找键,

var key = dictionary.FirstOrDefault(x => x.Value == "ab").Key; 

但我需要每个键都有一个值,其列表包含给定的部分名称。

【问题讨论】:

  • PushCycle.Where(kvp =&gt; kvp.Value.Contains(...)).Select(kvp =&gt; kvp.Key).ToList()

标签: c# list dictionary


【解决方案1】:

我认为您可以使用Where 过滤您想要的元素,然后使用Select 仅保留键来解决您的问题。

List<CarSystemPart> result = PushCycle
    .Where(e => e.Value.Contains(YourCarSystemPart)) // Filter elements that contains the CarSystemPart within their list
    .Select(e => e.Key) // Select the key of each element
    .ToList(); // Transform the IEnumerable<> into a List<>

【讨论】:

  • 我喜欢你的回答,除了 List 不能设置为字典类型。如果我将第一行更改为 var PushingParts = PushCycle intellisense 显示没有错误
  • 哎呀我的错误,确实应该是 PushCycle.Where ...
猜你喜欢
  • 2023-02-22
  • 2019-01-05
  • 1970-01-01
  • 1970-01-01
  • 2019-03-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-03-20
相关资源
最近更新 更多