Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I create a 2 dimensional dynamic length array?

I want to create a 2-dimensional array, without knowing the size of the first dimension.

For example I have an unknown number of rows, when I create an array. Every row represent an account. Exit 4 columns for every row: ID,name,user,password

I tried with jagged array but it is not possible to have:

int[][] jaggedArray = new int[][3];

Also I looked for ArrayList, implementation with clases and a little about Generics.

I'm searching for a solution that can permit easy manipulation of data as:

  • add to list,select,input elements
  • using elements in database queries
  • using as parameters in other functions

Because I'm a newbie in .NET (C#) please provide me with code solutions, instead of generic(look for) solutions

like image 738
user848568 Avatar asked Jul 17 '11 10:07

user848568


2 Answers

There is no such thing as dynamic length arrays in .NET. Use a List<> instead.

The array bounds all need to be known when you instantiate an array. What may have confused you is that this seems to be different for jagged arrays, but it's not: since it is an array of arrays, when you instantiate it it will be an array of uninstantiated arrays (e.g. null references). You then need to allocate each of those arrays again to use them.

like image 24
Lucero Avatar answered Oct 21 '22 23:10

Lucero


IMO, since the "columns" are fixed, declare a class for that:

public class Account
{
    public int ID {get;set;}
    public string Name {get;set;}
    public string User {get;set;}
    public string Password {get;set;} // you meant salted hash, right? ;p
}

now have a :

List<Account> list = new List<Account>();

this has everything you need:

add to list,select,input elements

list.Add etc

using elements in database queries using as parameters in other functions

vague without more info, but you can pass either the Account or invidual values, or the entire list.

like image 91
Marc Gravell Avatar answered Oct 21 '22 22:10

Marc Gravell