C # multidimensional array, ArrayList or hash table?

I am trying to figure out how to build a multidimensional "array" that:

  • flexible size
  • use 2 keys
  • 1st int key (flexible)
  • The second key is a string (limited view)

Usage will look like this:

console.writelen(array[0]["firstname"]);
console.writelen(array[0]["lastname"]);
console.writelen(array[0]["phone"]);

console.writelen(array[1]["firstname"]);
console.writelen(array[1]["lastname"]);
console.writelen(array[1]["phone"]);

.....
.....

console.writelen(array[x]["firstname"]);
console.writelen(array[x]["lastname"]);
console.writelen(array[x]["phone"]);
+5
source share
4 answers

Are you sure it would be impractical to create a class / structure for storing data? For instance:

class Person
{
    public string FirstName
    {
        get;
        set;
    }

    public string LastName
    {
        get;
        set;
    }

    public string Phone
    {
        get;
        set;
    }
}

Then you just create an array Person:

var array = new Person[1];
array[0] = new Person() { FirstName = "Joe", LastName = "Smith", Phone = "foo" };

Or, since you say "flexible size", perhaps you need a list instead:

var list = new List<Person>();
list.Add(new Person());

. , array[0] , ; :

var foo = new Person();
foo.FirstName = "John";

var bar = new Person() { FirstName = "John" };

, , list.Add(new Person() { ... }), . :

var john = new Person() { FirstName = "John" };
var joe = new Person() { FirstName = "Joe" };
var list = new List<Person>() { john, joe };
+10

:

Dictionary<int, Dictionary<string, string>>

:

var dd = new Dictionary<int, Dictionary<string, string>>();
dd[5] = new Dictionary<string, string>();
dd[5]["a"] = "foo";

:

class DDict { // optional: generic
    private readonly Dictionary<int, Dictionary<string, string>> _Inner = new ...;

    public Dictionary<string, string> this (int index) {
        Dictionary<string, string> d;
        if (!_Inner.TryGetValue(index, out d)) {
             d = new Dictionary<string, string>();
             _Inner.Add(index, d);
        }
        return d;
    }
}

var dd = new DDict();
dd[5]["a"] = "hi";

, , , :

var dd = new Dictionary<string, string>[128];

, , :

class Dat {
    string name;
    string phone;
}
var list = new Dat[128]

// access:
list[5].name = "matt";

List Dictionary<int, Dat> .

+4

I don’t think you can do it with Array if you don’t have one array of KeyValuePair <int, string>, but I think you really need a dictionary <int, string>.

var dic = new Dictionary<int,string>();
dic[0] = "zero";
dic[1] = "one";
dic[2] = "two";

foreach(KeyValuePair<int,string> kvp in dic)
{
   Console.WriteLine(String.Format("Key: {0}, Value: {1}",kvp.Key,kvp.Value);

}
0
source

In fact, I just see two dimensions. The first is the row index, the second is the column index. And that sounds like a DataTable to me.

0
source

All Articles