How to initialize an array constant with the desired indices

I just want to initialize the array constant string [], specifying not only the values, but also the indices to which they will be bound.

For example, on:

private static readonly string [] Pets = new line [] {"Bulldog", "GreyHound"};

I would like to say that BullDog corresponds to index 29 and GreyHound to 5 (like php :))

Any suggestion?

Greetings

+3
source share
6 answers

If you have some flexibility regarding the data structure, it would be more efficient to use an Dictionary<int, string>array for this behavior instead.

Example (if you use C # 3 or higher):

var pets = new Dictionary<int, string> {
    { 29, "Bulldog" },
    { 5, "Greyhound" }
};
Console.WriteLine(pets[5]);

:

Dictionary<int, string> pets = new Dictionary<int, string>();
pets[29] = "Bulldog";
pets[5] = "Greyhound";
Console.WriteLine(pets[5]);
+7

, , Dictionary<int, string>, :

private static readonly Dictionary<int, string> pets = 
    new Dictionary<int, string> {
    { 29, "Bulldog" },
    { 5, "Greyhound" }
};

( , # 3. , Add .)

, :

string x = pets[29];
pets[10] = "Goldfish";
+6

, , , # .

Dictionary, , , ( Description), .

private enum Pets
{
   [Description("GreyHound")]
   Greyhound = 5,
   [Description("Bulldog")]
   Bulldog = 29
}
+1

, Dictionary, , . , , :

public static T[] CreateArray<T>(params Tuple<int, T>[] values)
{
    var sortedValues = values.OrderBy(t => t.Item1);

    T[] array = new T[sortedValues.Last().Item1 + 1];

    foreach(var value in sortedValues)
    {
        array[value.Item1] = value.Item2;
    }

    return array;
}

:

string[] myArray = CreateArray(new Tuple<int, string>(34, "cat"), new Tuple<int, string>(12, "dog"));

# Tuple, , -, , .

? , , .

+1

, Dictionary.

, ( ):

Dictionary<int, string> d = new Dictionary<int, string>();
        d.Add(2, "cat");
        d.Add(1, "dog");
        d.Add(0, "llama");
        d.Add(-1, "iguana");
0

, , .

private static readonly string[] Pets = new string[42];

and then in the static constructor you insert your elements.

private static MyClass
{
    Pets[29] = "Bulldog";
    Pets[5] = "Greyhound";
}

But as others suggested: use Dictionary<int, string>.

0
source

Source: https://habr.com/ru/post/1761187/


All Articles