开发者

Defining two dimensional Dynamic Array

How can I define two开发者_如何学编程 dimensional dynamic array? If I want to use List<>, can I use it for two dimensions?


There's no built-in dynamic equivalent of two-dimensional arrays that I'm aware of, but you can easily get at more or less the same functionaltiy.

Define a 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...
}

You can now create a collection of these Coordinate instances.

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

If you want, you can expand Coordinate to Coordinate<T> like this:

public class Coordinate<T> //...
{
    // previous stuff...

    public T Item { get; set; }
}

This will allow you to associate a strongly typed item with each coordinate, like this:

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


This would be something like this:

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

But I think it is impractical to use a List for this, better resort to arrays...


you can use list e.g. List> and list in c# is very fast.

but by two-d array you need something like:

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

and this should be the more faster than list.


You should take a look here: Arrays Tutorial in C#. Anyway here is the syntax: type[,] name for multidimensional arrays, type[][] name for jagged arrays (change type for the type of the objects to be stored in the array).


With arrays you cant, they are never 'dynamic'.

With lists you cant either (unless you make it look like one by providing an additional indexer), unless you are simply looking for a list of lists (which is not multi-dimensional).

That would be (for a list of list of string):

List<List<string>>


Dictionary<T, List<T>>

for example, if T was "string" you can use it like this:

var pathes = new Dictionary<string, List<string>>();

pathes.Add("X", new List<string>());
pathes["X"].Add("a");
pathes["X"].Add("b");
pathes["X"].Add("c");

pathes.Add("Y", new List<string>());
pathes["Y"].Add("b");
pathes["Y"].Add("z");
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜