How to create a two-dimensional array of dynamic length?

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

For example, I have an unknown number of rows when I create an array. Each line represents an account. 4 columns for each row: ID, name, user, password

I tried using jagged array, but this is not possible:

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

I also searched for ArrayList , an implementation with clans and a bit about Generics.

I am looking for a solution that makes it easy to manipulate data like:

  • add to list, select, enter items
  • using items in database queries
  • use as parameters in other functions

Since I'm new to .NET (C #), please provide me code solutions, not general (look for) solutions.

+8
arraylist arrays c # dynamic
source share
3 answers

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

 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:

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

this has everything you need:

add to list, select, enter items

list.Add etc.

use of elements in database queries using other functions as parameters

undefined without additional information, but you can pass either Account , or invidual values, or the entire list.

+17
source share

In .NET, there is no such thing as dynamic-length arrays. Use List<> instead.

All array boundaries must be known when creating an instance of the array. What may confuse you is that for jagged arrays this seems different, but it is not: since it is an array of arrays, when you create it, it will be an array of unlit arrays (e.g. null references). Then you will need to allocate each of these arrays for their use.

+2
source share

As long as I know, we cannot create an array of instances without knowing its size. Why aren't you trying to create an array from a list? Like this:

 List<int>[] a = new List<int>[yourDesireColumnNumber]; 

Using List, add, select, input elements are trivial. If you want to specify it as a parameter in other functions, just define the type.

0
source share

All Articles