How do I initialize while declaring a multidimensional array in C#?

Asked 2 years ago, Updated 2 years ago, 427 views

It's exactly the same as the title.
For example, PHP can declare and initialize variables simultaneously as follows:

$arr=[
  "arr1" = > [
    "val1", "val2", "val3"
  ],
  "arr2" = > [
    "val4", "val5"
  ],
  "arr3" = > [
    "val6", "val7"
  ],
];

If you nest array elements, theoretically you can initialize while declaring an infinite number of multidimensional arrays.
Similarly, how do I initialize while declaring a multidimensional array in C#?

c# array

2022-11-14 16:23

2 Answers

Isn't it strictly multidimensional array associative array that the associative array?
Sample PHP associative and multidimensional arrays

It looks like you have more keys (arrX) and an array of values (valY...).
Moreover, the number of values in the array seems to be arbitrary.

You can easily define and initialize a multidimensional array with C# only values.(Example is an array of int)
Multidimensional Array (C# Programming Guide)

Then, if the number of elements is not the same, we initialize them in a slightly different way under the name of the jug array.
Jug array (C# programming guide)
For example, if you approach an example of a question, it looks like this.(You cannot specify a key)

 string [ ] [ ] arr = {
    new string [ ] {"val1", "val2", "val3"},
    new string [ ] {"val4", "val5"},
    new string [ ] {"val6", "val7"}
};

However, if you want to get closer to the associative array, you will use the Dictionary type in C#.
How to use associative arrays in C#
[C#]How to use Dictionary (Summary of how to use associative arrays)

It will look like the following

Dictionary<string, string[]>arr=new Dictionary<string, string[]>()
{
    {"arr1", new string[]{"val1", "val2", "val3"}},
    {"arr2", new string[]{"val4", "val5"}},
    {"arr3", new string [ ] {"val6", "val7"}
};

Alternatively, the array of values can be List.

Dictionary<string, List<string>>arr=new Dictionary<string, List<string>>()
{
    {"arr1", new List <string > {"val1", "val2", "val3"}},
    {"arr2", new List <string > {"val4", "val5"}},
    {"arr3", new List <string > {"val6", "val7"}
};


2022-11-15 07:35

In addition to Kunif's response, there is also a Lookup class.However, since no constructor is provided, it cannot be initialized while declaring.It can be built with the ToLookup() extension method.

using static System.Collections.Generic.KeyValuePair;
vararr=new[]{
    Create("arr1", "val1",
    Create("arr1", "val2",
    Create ("arr1", "val3"),
    Create ("arr2", "val4"),
    Create ("arr2", "val5"),
    Create("arr3", "val6",
    Create ("arr3", "val7"),
}.ToLookup(p=>p.Key,p=>p.Value);


2022-11-15 09:10

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.