Reputation: 173
I'm new in C# and my question is, exist on C# arrays like PHP for example
$array = array("name" => array(), "Age" => array());
I want to know if is possible to make an array like that on C#
Upvotes: 0
Views: 158
Reputation: 728
You could create your own class
public class People{
public List<string> Names { get; set; }
public List<int> Ages { get; set; }
}
this will allow you to have a class with a list of names and a list of ages. Though I don't think this is really want you want to do or perhaps a better response is: There is a better way to do what you want to do which looks like you want to loop through some names and their RELATED ages.. in which case, you would be better off with something like this:
public class Person{
public int Age { get; set; }
public string Name { get; set; }
}
List<Person> people =new List<Person>{
new Person{Age=20,Name="Bob"},
new Person{Age=25,Name="Sue"},
};
Now you have OBJECTS to work with that hold information in a more relational manner. This will completely avoid having to associate by index.
Upvotes: 0
Reputation: 1993
The closest you can get is a Dictionary<string, string[]>
This gives you the hashtable-type string lookup that returns an array. Note that you need to replace string[]
with an array of the type that you want to store.
Lookups then work like this:
var dict = new Dictionary<string, string[]>() {
{ "name", new string[] { "Bob", "Sally" } },
{ "age", new string[] { "twenty four", "twenty three" } }
}
That being said, that's not the C# way of storing data. I'm going to go out on a limb and guess that you're storing a list of people. In C# you're much better off creating a class Person
with attributes Name
and Age
, then populating and holding a list of the people. Example:
public class Person {
public string Name { get; set; }
public int Age { get; set; }
}
var bob = new Person { Name = "Bob", Age = 24 };
var sally = new Person { Name = "Bob", Age = 23 };
var people = new List<Person>() { bob, sally };
Upvotes: 1