【问题标题】:How do I map List values to a new objects properties如何将列表值映射到新对象属性
【发布时间】:2020-11-16 00:08:57
【问题描述】:

我有一本像这样的字典

public Dictionary<string, List<string>> Options { get; set; }

如您所见,它将字符串作为Key,将列表形式的字符串集合作为Value

目标是创建多个 ProductVariant 类型的对象,它们具有 3 个属性。 Option1Option2Option3

对于Options 中的每个Value,我想将Option1 设置为Option[0] 值,然后Option2 属性获取Option[1] 值。

我尝试做这样的事情,但它只获得了其中一个属性并且它不起作用,因为这不是我想要完成的。

foreach (var thing in item.Options.ElementAt(0).Value)
{
    variants.Add(new ProductVariant
    {
        Option1 = thing
    });
}

所以底线.. 我想将 Option1Option2 分配给字典中每个项目的相应值。

像这样

我该如何正确地做到这一点?

【问题讨论】:

  • 您的 ProductVariant 必须具有字典所在的属性。然后您创建 3 个其他属性,其中 get 给出了该词典的正确索引结果。 var test = new ProductVariant(yourDictionnary) test.Option1 test.Option2 test.Option3 public string Option1 => _myDictionnary[0];公共选项2 => _my....[1]等等
  • 不幸的是,它不能,因为它是第三方库。
  • 那么,Options 中的每个键都应该有一个对应的 ProductVariant 项,其值来自字典值?
  • 是的,就像我尝试用图片描述它一样,我尽力了哈哈

标签: c# .net dictionary enumerable


【解决方案1】:

一种方法是使用反射,如下例所示:

public class ProductVariant
    {
        public ProductVariant()
        {
            
        }
        public string Key { get; set; }
        public string Option1 { get; set; }
        public string Option2 { get; set; }
        public string Option3 { get; set; }

        public static IEnumerable<ProductVariant> GetProductVariants(Dictionary<string, List<string>> options)
        {
            foreach (var optionList in options)
            {
                var pv = new ProductVariant();
                pv.Key = optionList.Key;

                var props = pv.GetType()
                    .GetProperties()
                    .Where(x=>x.CanWrite && x.CanWrite)
                    .Where(x=>x.Name!="Key")
                    .ToArray();

                for (int i = 0; i < props.Length; i++)
                {
                    props[i].SetValue(pv,optionList.Value[i]);
                }

                yield return pv;
            }
        }
    }

我测试了这个方法并且正在工作。您仍然需要进行一些验证以避免错误。

方法可以看这里:https://dotnetfiddle.net/KCKhaS

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-01-01
    • 2017-05-22
    • 1970-01-01
    • 2010-10-18
    • 2022-08-18
    • 2019-03-30
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多