1
var movieNext = new string[,]
{
    { "superhero", "action", "waltdisney", "bat"}, 
    {"superhero", "action", "marvel",""}, 
    {"history", "action", "malay", "" },
    {"malay", "novel", "", ""}, 
    {"history", "bat", "", ""}
};

The above code is a multidimensional array, which stores a sequence of movie's keyword. Is there a way to implement this without having to put the blank strings in the array initialization?

For example you can see in the above code, I have to put the blank string "" to fill up the array.

3 Answers 3

2

You could use a jagged array instead.

string[][] movieNext = new string[][] { { etc... } }.
Sign up to request clarification or add additional context in comments.

Comments

1

You can consider C# jagged array (though they are different from multi-dimensional arrays).

string[][] movieNext =  {
new [] { "superhero", "action", "waltdisney", "bat"},
new []  {"superhero", "action", "marvel"}, <and so on>
};

If you want to stick with multi-dimensional arrays, you have to initialize the values individually. If you don't provide any string value for any of the index (i,j) by default it will be null.

Comments

0

I suggest never to use two-dimensional arrays. They have practically no support in the API (you'll be hard pressed to find a method that accepts a two-dimensional array as a parameter), and cannot be cast to IEnumerable<T> or similar well-supported interface. As such, you can really use them only in the most local of scopes.

Instead, I suggest you use something castable to IEnumerable<IEnumerable<string>>. Oh, another tip. Check this out. Specifically,

To initialize a Dictionary, or any collection whose Add method takes multiple parameters, enclose each set of parameters in braces as shown in the following example.

Thus, the following will work:

class Program
{
    static void Main(string[] args)
    {
        var d = new ManyList()
        {
            {"Hi", "Good", "People", "None", "Other"}
            {"Maybe", "Someone", "Else", "Whatever"}
        };
        Console.Read();
    }
}

class ManyList : List<string>
{
    public void Add(params string[] strs)
    {
        Console.WriteLine(string.Join(", ", strs));
    }
}

This might help you clean up your syntax a bit.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.