【问题标题】:Dictionary key from a nested object list嵌套对象列表中的字典键
【发布时间】:2023-03-29 02:23:02
【问题描述】:

我有一个对象列表 lstItems (Type - Item)

本例中带有嵌套对象列表 Variants(Type Variant)

我需要创建一个字典,其键将是嵌套对象上的 SKU 字段

例子:

项目对象类型

       Title 
       Quantity 
       Variants ( List of Variant)

变体对象类型

       SKU 
       picture

例如关于变体的数据

变体 1

SKU:AAAA

图片:“Blblb.jpg”

变体 2

SKU:BBBB

图片:“Blblbsd.jpg”

在一个美丽的世界中,我将能够执行此代码并且它有效(下) 如何将所有 SKU 作为对象项的键

   Dictionary<string, Product> identityMap1 
     = lstItems.ToDictionary(item => item.Variants.Select(y => y.SKU).ToList());

【问题讨论】:

    标签: c# dictionary


    【解决方案1】:

    看来,您正在寻找SelectMany展平内部列表:

    var identityMap1 = lstItems
      .SelectMany(item => item
         .Variants
         .Select(inner => new {
            key   = inner.SKU,
            value = inner.Picture //TODO: Put the right value here: is it inner? item?
          }))
      .ToDictionary(item => item.key, item => item.value);
    

    【讨论】:

      猜你喜欢
      • 2021-05-10
      • 2021-10-20
      • 1970-01-01
      • 2020-12-15
      • 1970-01-01
      • 2022-11-21
      • 2021-10-27
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多