views:

75

answers:

6

Hello StackOverflowers,

What I just want is to initialize a string[] array constant by specifying not only the values, but the indexes they will be attached to.

For example, on:

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

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

Any suggestion?

Cheers,

+7  A: 

If you have some flexibility in terms of your data structure, it would be more efficient to use a Dictionary<int, string> instead of an array for this behavior.

Example (if you are using C# 3 or above):

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

Same example for legacy applications:

Dictionary<int, string> pets = new Dictionary<int, string>();
pets[29] = "Bulldog";
pets[5] = "Greyhound";
Console.WriteLine(pets[5]);
Ben Hoffstein
Thanks Ben, finally I implemented your solution. I used System.Collections.Generic.KeyValuePair<TKey, TValue> too.
Ramon Araujo
A: 

You don't need a string array, but instead a Dictionary.

Take a look at link text, there's a fine example there (which I adapted here):

Dictionary<int, string> d = new Dictionary<int, string>();
        d.Add(2, "cat");
        d.Add(1, "dog");
        d.Add(0, "llama");
        d.Add(-1, "iguana");
Paulo Guedes
The other answers are more intuitive for use, with `int` being the key and `string` being the value. This answer assumes you know the values rather than the desired "index" positions.
Anthony Pegram
you're right, thanks. edited my answer.
Paulo Guedes
+5  A: 

It sounds like you don't want an array, but a Dictionary<int, string> instead, which could be initialized like this:

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

(Note that this collection initializer syntax was only added in C# 3. If you're using an older version you'll have to call Add or the indexer explicitly multiple times.)

You can access a dictionary via its indexer which looks like array access:

string x = pets[29];
pets[10] = "Goldfish";
Jon Skeet
+1 - this is the only answer that shows creation and initialization in the same line, although other answers are generally correct. You beat me to as usual Jon ;)
womp
I changed my answer to use an initializer since I agree with your comment. Also, there's a small typo (: instead of ;)
Ben Hoffstein
@Ben: Fixed, thanks.
Jon Skeet
+1  A: 

I don't think what you want is possible in C# when declaring arrays.

Besides using a Dictionary as others have suggested, you could try using an enumeration instead, with values corresponding to your specific array indices and descriptions (using the Description attribute) corresponding to the string values.

private enum Pets
{
   [Description("GreyHound")]
   Greyhound = 5,
   [Description("Bulldog")]
   Bulldog = 29
}
Bernard
Not to be pedantic, but it's possible to use an array initializer to assign null to everything except the 5th and 29th elements. If I saw that in the wild though, I might shoot the perpetrator :-)
Ben Hoffstein
I would too Ben.
Bernard
A: 

You can not do that in the initializer, you need to first specify the size of the array and then add items at specific locations.

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

and then in a static constructor you insert your items.

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

But as other have suggested: use the Dictionary<int, string>.

Albin Sunnanbo
A: 

For the record, I agree with everyone that a Dictionary is probably more appropriate. But you can write a little method to pull off what you want:

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;
}

And call it like this:

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

If C# receives the syntactic sugar for Tuple that many people seem to want, this would get a tad cleaner looking.

Is this a good idea? Almost certainly not, but I'll leave that for the OP to judge.

Matt Greer