简体   繁体   中英

Questions about 2D lists C#

I've ran into an issue with lists as I need to create a 2-dimensional list where I can read data by giving the columns and rows, so I could read from my list by using my_List[col][row] so is it possible making a 2D list that way?

How much performance impact can this have and anything I should be aware that could have a performance impact on the code? I might need to read a few hundred times per second from my 2D list

Is it possible to have a more grid type 2D list so if i have data in 3, 4 and 5 but i dont have anything in 0, 1, and 2 think of it like coordinates. so can I read from the list using myList[3][5] and get the data from there with 0, 1 and 2 having nothing? or do i need to loop it through and add something there like null?

thanks in advance!

Yes, you can indeed use multidimensional arrays or jagged arrays for storing "2D data".

As for creating a data structure that doesn't use any memory space for unused indexes, an option could be to use a dictionary where the keys are tuples of two numbers, like this (assuming that your data are strings):

var items = new Dictionary<(int, int), string>();

items.Add((0,1), "0-1"); //this throws an error if the key already exists
items[(2,3)] = "2-3";    //this silently replaces the value if the key already exists

Console.WriteLine(items.Keys.Contains((0,1))); //true
Console.WriteLine(items.Keys.Contains((0,2))); //false

Console.WriteLine(items[(2,3)]); //"2-3"

Of course you probably want to encapsulate this functionality in its own class, but you get the idea.

Note however that this dictionary approach will probably be worse than a plain array in terms of performance, but it's up to you to experiment and collect some metrics.

You can create 2D Arrays like this :

string[,] twoDArray = new string[2,2];

Then you can loop through it like :

        for (int i = 0; i < twoDArray.Length; i++)
        {
            foreach (int j in twoDArray[i,0])
            {

            }
        }

You can also create 2D Lists like this:

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

and iterate through them using an Enumerator and for example a for loop:

 var enu = grid.GetEnumerator();
            while (enu.MoveNext())
            {
                for(int i = 0; i < enu.Current.Count; i++)
                {
                    enu.Current.RemoveAt(i);
                }
            }

You are basically iterating over all lists and then through each list as long as its size is. Inside the for loop you can alter the encapsuled lists in whatever way you like.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM