Swathi
Swathi

Reputation: 25

How to add Dictionary values to a Collection in C#?

I am working on a C# test and in here I have ICollection<ProductVariant> and ProductVariant has name field which is a Dictionary. I want to have multiple ProductVariants for my testing.

what I have done is

ICollection<ProductVariant> productVariants = new Collection<ProductVariant>();

Now I want to add different product variants to this collection

productVariant.Add(new ProductVariant()
{
// I want to initialize Name here which is a dictionary

Name = new Dictionary<string, string>("var1", "variant1")
};

But this is not working.

Upvotes: 1

Views: 489

Answers (1)

Yehor Androsov
Yehor Androsov

Reputation: 6162

Inline initialization for dictionary looks a bit different

productVariant.Add(new ProductVariant()
{ 
    Name = new Dictionary<string, string>()
    {
        { "var1", "variant1" },
        { "var2", "variant1" }
    }
};

Alternatively, you could assign local variable to a property. I like this approach more because of good stacktrace in case of error

var nameDict = new Dictionary<string, string>();
nameDict.Add("var1", "variant1");
nameDict.Add("var2", "variant1");

productVariant.Add(new ProductVariant()
{ 
    Name = nameDict
};

Upvotes: 6

Related Questions