Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the C# equivalent of a Javascript array of key/value pairs

Tags:

javascript

c#

What does this represent in javascript:

[["January", 10], ["February", 8], ["March", 4], ["April", 13], ["May", 17], ["June", 9]]

And secondly, what is the C# equivalent?

Array of arrays?? But each inner array is essentially a key/value pair, so that's not right.

How would one generate this JS object in C#?

like image 331
coach_rob Avatar asked Dec 02 '22 11:12

coach_rob


1 Answers

If it’s a map, then the equivalent for efficient lookups in C# would be a Dictionary<TKey, TValue>:

var months = new Dictionary<string, int>()
{
    {"January", 1}, {"February", 2}, {"March", 3},
    {"April", 4}, {"May", 5}, {"June", 6}
};

Now, if it’s an array of tuples, C# 7 has native tuple support:

var months = new[] 
{
    ("January", 1), ("February", 2), ("March", 3),
    ("April", 4), ("May", 5), ("June", 6)
};

And you can even name the members of the tuple like so:

var months = new (string Name, int Number)[]
{
    ("January", 1), ("February", 2), ("March", 3),
    ("April", 4), ("May", 5), ("June", 6)
};

Console.WriteLine(months[0].Name);
like image 154
InBetween Avatar answered Dec 06 '22 11:12

InBetween