Riley Varga
Riley Varga

Reputation: 720

How do I map List values to a new objects properties

I have a dictionary that looks like this

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

As you can see it takes a string as the Key and a collection of strings in the form of a list as the Value

And the goal is to create multiple objects of type ProductVariant which has 3 properties. Option1, Option2 and Option3

For each Value in the Options I want to set the Option1 to the Option[0] value and then the Option2 property gets the Option[1] value.

I tried doing something like this but it only gets one of the properies and it doesnt work because that's not what I was trying to accomplish.

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

So bottom line.. I want to assign Option1 and Option2 to the corresponding values from the dictionary for each item in there.

Like this enter image description here

How do I properly do this?

Upvotes: 0

Views: 1369

Answers (1)

Lucian Bumb
Lucian Bumb

Reputation: 2881

One way is to use reflection, like in the below example:

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;
            }
        }
    }

I tested this method and is working. You still need to put some validation to avoid errors.

you can see the method here: https://dotnetfiddle.net/KCKhaS

Upvotes: 1

Related Questions