Shaakir
Shaakir

Reputation: 484

Multidimensional associative array C#

Coming from PHP background I could do this in PHP:

$array[sales_details][uid] = 1;
$array[sales_details][name] = "Name Surname";
$array[sales_details][sales][France][Paris] = 50;
$array[sales_details][sales][France][Lyon] = 25;
$array[sales_details][sales][UK][London] = 75;
$array[sales_details][sales][German][Berlin] = 23;

How can I do this in C#? I tried looking into Dictionary. But even if I define the value key as object it will not accept the "sales" array.

var dict = new Dictionary<string, object>();
dict["uid"] = 1;
dict["sales"]["France"]["Paris"] = 50; //error kicks in here

Is this possible with C#?

Upvotes: 2

Views: 882

Answers (2)

ChoockY
ChoockY

Reputation: 94

When you want dynamic properties, try to use the ExpandoObject class like this:

dynamic salesDetails = new ExpandoObject();
salesDetails.Uid = 10;

salesDetails.Sales = new ExpandoObject();

salesDetails.Sales.France = new ExpandoObject();
salesDetails.Sales.France.Paris = 50;
salesDetails.Sales.France.Lyon = 25;

salesDetails.Sales.UK = new ExpandoObject();
salesDetails.Sales.UK.London = 75;

salesDetails.Sales.Germany = new ExpandoObject();
salesDetails.Sales.Germany.Berlin = 23;

dynamic london = salesDetails.Sales.UK.London;

It is important, that you have to initialize also the inner properties as ExpandoObject.

Upvotes: 0

Patrick Hofman
Patrick Hofman

Reputation: 156978

It seems to me you are trying to put a lot of information in an array, what actually has to be an object.

You can solve this with jagged arrays, but objects are way better.

Create a class like this:

public class SalesDetails
{
    public string Uid {get;set;}
    public string Name {get;set;}

    public List<SalesItem> SalesItems {get;set;} = new List<SalesItem>();
}

Then work out yourself SalesItem, City and all other objects you need.

Upvotes: 2

Related Questions