Multidimensional array in C# equal PHP?

Asked

Viewed 231 times

0

First time here on this forum, I usually use stack overflow but come on.

My question refers to the array in C#: I’m more familiar with PHP and in php we can name our array indexes for example:

$array = ["nome"=>"Pedro", "Idade"=>18];

My question is, is it possible to name the indexes of an array in C#?

if not, taking advantage of the post, question 2: in an array built that way:

string[,] array = new string[,]
{
   {"nome0", "idade1"},
   {"nome0", "idade1"}
};

As I would in a foreach to catch in each passage always the name and the corresponding age?

  • Did any of the answers solve your problem? Do you think you can accept one of them? If you haven’t already, see [tour] how to do this. You would help the community by identifying the best solution for you. You can only accept one of them, but you can vote for any question or answer you find useful on the entire site.

  • "First time here on this forum, I usually use stack overflow but come on." What is this site? :)

2 answers

6

I’m going to show you several ways to do all of this, this one has been scratching at being more than one question.

We start by creating a dictionary that is the equivalent of array associative of PHP.

var dict = new Dictionary<string, string> {["nome"] = "Pedro", ["Idade"] = "18"};
foreach (var item in dict) {
    WriteLine($"{item.Key} => {item.Value}");
}

Since C# is a typed language, it is necessary to indicate the type of the key and the value. So you can’t mix types like you did in the PHP example. There’s a way to solve this, but it’s not usually suitable in C#. Just use the type object which accepts anything. Thereby loses the security of language types. So:

var dict2 = new Dictionary<string, object> {["nome"] = "Pedro", ["Idade"] = 18};
foreach (var item in dict2) {
    WriteLine($"{item.Key} => {item.Value}");
}

It has other ways to achieve a similar effect, but I repeat, better avoid.

Using a array multidimensional can iterate through all items without worrying about the dimension. Remembering that typing counts here too, but the example of the question seems to already consider this.

var array = new string[,] {
   {"nome0", "idade1"},
   {"nome1", "idade2"}
};
foreach (var item in array) {
    WriteLine($"{item}");
}

But if you want to sweep the array considering the dimensions can not use foreach. Do so:

for (var i = 0; i < array.GetLength(0); i++) { //pega o tamanho da dimensão 0
    for (var j = 0; j < array.GetLength(1); j++) { //pega o tamanho da dimensão 1
        WriteLine($"{array[i, j]}");
    }
}

It is even possible to abstract the access and use the foreach. To do this you would need to create a class with an iterator method that returns the dimensions conveniently to use in foreach. I am not going to give an example because I think that this solution is not even the most appropriate.

In C# it is almost always more interesting to use Jagged array (array of array) than a array multidimensional.

var jaggedArray = new string[2][] {new string[2] {"nome0", "idade1"}, new string[2] {"nome1", "idade2"}};
foreach (var subArray in jaggedArray) {
    foreach (var item in subArray) {
        WriteLine($"{item}");
    }
}

But it seems that what you really want is to create a class with a specific object and create a list. In PHP it is used array for everything. C# is more optimized and has a mechanism for every need. For example a list seems to be better than a array. And that the other dimension seems to be just a different way of using the array associative that is common in PHP (although the language accepts classes as well, but that by its nature is not usually used for this).

var listaPessoas = new List<Pessoa> {
    new Pessoa {Nome = "Pedro", Idade = 18},
    new Pessoa {Nome = "João", Idade = 15}
};
foreach (var item in listaPessoas) {
    WriteLine($"{item.Nome} => {item.Idade}");
}

public class Pessoa {
    public string Nome { get; set; }
    public int Idade { get; set; }
}

In some cases a struct can be better than a class.

In fact it would be possible to use a tuple to avoid creating a class that is not always desirable (I don’t think that is the case) that until version 6 was not convenient. In C# 7 is much more convenient in some cases other than this.

Behold working in the ideone. And in the .NET Fiddle. Also put on the Github for future reference.

Obviously I used more modern techniques throughout the code.

Documentations:

1

Hello, good morning.

For your second question, you can make a foreach this way:

 class Program
{
    static void Main(string[] args)
    {
        string[,] array = new string[,]
       {
           {"nome0", "idade1"},
           {"nome1", "idade2"}
       };

        foreach (var item in array)
        {
            Console.WriteLine(item);
        }
        Console.ReadKey();
    }
}

For the first question, I don’t know if I get it, but if it’s a list with key and value, you could do it like this:

class Program
{
    static void Main(string[] args)
    {
        Dictionary<string, string> array = new Dictionary<string, string>();
        array.Add("nome", "Joao");
        array.Add("nome2", "Akame");

        foreach (var item in array)
        {
            Console.WriteLine(item.Value);
        }
        Console.ReadKey();
    }
}

To learn more about Dictionary: https://msdn.microsoft.com/pt-br/library/xfhwa508(v=vs.110). aspx

Browser other questions tagged

You are not signed in. Login or sign up in order to post.