Definition of a two-dimensional dynamic array

How to define a two-dimensional dynamic array? If I want to use List <>, can I use it for two dimensions?

+4
source share
5 answers

There is no built-in dynamic equivalent of two-dimensional arrays that I know of, but you can easily get more or less the same functional.

Define the Coordinate class with this API:

public class Coordinate : IEquatable<Coordinate> { public Coordinate(int x, int y); public int X { get; } public int Y { get; } // override Equals and GetHashcode... } 

Now you can create a collection of these Coordinate instances.

If you create a HashSet<Coordinate> , you will be guaranteed that you cannot add coordinates if it is already added because it overrides Equals.

If you want, you can expand the coordinate to Coordinate<T> as follows:

 public class Coordinate<T> //... { // previous stuff... public T Item { get; set; } } 

This will allow you to associate a strongly typed element with each coordinate, for example:

 var items = new HashSet<Coordinate<string>>(); items.Add(new Coordinate<string>(1, 4) { Item = "Foo" }); items.Add(new Coordinate<string>(7, 19) { Item = "Foo" }); // ... 
+10
source

you can use a list, for example. List> and the list in C # is very fast.

but with a two-dimensional array you need something like:

 int[,] arr = new int[100,100]; 

and it should be faster than the list.

+2
source

You should look here: A tutorial on arrays in C # . In any case, here is the syntax: type[,] name for multidimensional arrays, type[][] name for jagged arrays (changing type for the type of objects that will be stored in the array).

+1
source

It will be something like this:

 List<List<string>> twoDimensional = new List<List<string>>(); 

But I believe that using this list is impractical, it is better to resort to arrays ...

+1
source

With arrays that you cannot, they are never "dynamic".

With lists that you cannot use (unless you make it look like one by specifying an extra pointer), if you are simply not looking for a list of lists (which is not multidimensional).

This will be (for a list of string list):

 List<List<string>> 
0
source

All Articles