This question already has answers here:
How to resize multidimensional (2D) array in C#?
(7 answers)
Closed 5 years ago.
I'm trying to use a multidimentional string array.
I can easily create it:
string[,] array = new string[,]
{
{"AA", "AB"},
{"AC", "AD"},
};
no issue here.
The idea is to add some more items after.
The assumption is that my array can be extended for many "rows" but just two "columns".
I've tried to do this:
array[0,0] = "AE";
array[0,1] = "AF";
but this does not seem to work. Why?
Also is there any way to add (concatenate/join?) e.g. in one go:
new string[,] { {"AE", "AF"} }
or
array[i,???] = {"AE", "AF"}
where i can be variable (e.g. to the last position) and the columns wouldn't have to be defined (based on 2 columns defined in the array)
this could add the new item into the existing array (at 3rd position)?
The string[,] is a very good solution to set up your items manually, but if you have external data that requires to be added to the array, I couldn't find any example it on any other posts.
Can someone help?
Thanks.
Regards,
you need a datastructure that can grow ( and shrink )
try :-
var array = new List<string[]> {new[] {"AE", "AF"}, new []{"A", "B"}};
and then
array.Add(new []{"XY", "AB"});
and you can access it like :-
Console.WriteLine(array[0][0]);
array[0][0] = "BB";
Console.WriteLine(array[0][0]);
If you like array initialization syntax, you can do that first and convert it to a list like :-
var initial = new[,] {{"H", "I"}, {"R", "V"}};
var array = Enumerable.Range(0, initial.GetUpperBound(0) + 1)
.Select(n => new[] {initial[n, 0], initial[n, 1]}).ToList();
Related
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.
I'm new in C# and i was wondering if it is possible to store two dimensional arrays in a List or Observable Collection like this : ObservableCollection<double[,]> TwoDarray = new ObservableCollection<double[,]>(); and access each List element(the arrays in our case) with an index which points to specific elements(arrays) of the List.For example i want to plot some data from a custom class and i want to make a combobox which you can select and plot previous inputs if the user wants to plot previous inputs.
If you want to use the multidimensional array you mentioned in your post
double[,]
then you can create a list of those objects
Like:
List<double[,]> TwoDarray = new List<double[,]>();
Then to add one to the array you just use the list .add method
TwoDarray.add(new double[,]);
To access your new array you can simply use your
var x = TwoDarray[0];
Are you looking for something like this?
List<int[,]> myList = new List<int[,]>();
myList.Add(new int[,] {{1, 2}});
myList.Add(new int[,] {{3, 4}});
myList.Add(new int[,] {{5, 6}});
Console.WriteLine(myList[0][0, 0]); // Output: 1
Console.WriteLine(myList[2][0, 1]); // Output: 6
This question already has answers here:
Convert 2 dimensional array
(4 answers)
Closed 7 years ago.
Is there an elegant way to flatten a 2D array in C# (using Linq or not)?
E.g. suppose
var my2dArray = new int[][] {
new int[] {1,2,3},
new int[] {4,5,6}
};
I want to call something like
my2dArray.flatten()
which would yield
{1,2,3,4,5,6}
Any ideas?
You can use SelectMany
var flat = my2dArray.SelectMany(a => a).ToArray();
This will work with a jagged array like in your example, but not with a 2D array like
var my2dArray = new [,] { { 1, 2, 3 }, { 1, 2, 3 } };
But in that case you can iterate the values like this
foreach(var item in my2dArray)
Console.WriteLine(item);
I am creating an array of arrays such that:
var arrNewArray = new string[arrOldArray.Length][7];
arrOldArray is an array of arrays such that it's [X][4], meaning the length of the 1st array or "outside" array can change, but the length of the "inside" array is ALWAYS 4, or hold 4 strings ([0][1][2][3]).
Why won't the compiler accept my statement above?
Essentially, I'm trying to take arrOldArray and expand it, or add a few more "columns" by increasing the [4] in the old array to a [7] in the new array and then copy the contents over. Perhaps I'm not doing it the best/efficient way, so any guidance would be appreciated thanks.
I think you want a two dimensional array:
var arrNewArray = new string[arrOldArray.Length, 7];
You would access it like this: arrNewArray[x, y].
This is better than a jagged array, because it clearly communicates that the number of "columns" is the same for every row.
If you want to continue using a jagged array, you need to do it like this:
var arrNewArray = new string[arrOldArray.Length][];
for(int i = 0; i < arrOldArray.Length; ++i)
arrNewArray[i] = new string[7];
The reason for this convoluted way is: With a jagged array, each "row" can have a different number of "columns". A short-hand syntax for the case where each "row" has the same number of "columns" doesn't exist. That's why your code doesn't compile.
A jagged array is essential an array of arrays, so you need to create a new array instance for each "row" of the outer array and explicitly assign it. That's what the for loop is doing.
You can't use Array.Copy with jagged arrays. Each child-array is it's own instance and Array.Copy doesn't make a deep copy, it merely copies the references from one array to another. The effect would be, that both arrays would point to the same items and changing an item in one array would be seen from the other.
You are not creating the jagged array properly. The proper way is to create the first dimension of the jagged array and then loop through the items of the first dimension to create the nested arrays and copy the data from the old arrays. Here's an example:
int newSize = 7;
string[][] newArray = new string[oldArray.Length][];
for (int i = 0; i < oldArray.Length; i++)
{
newArray[i] = new string[newSize];
Array.Copy(oldArray[i], newArray[i], oldArray[i].Length);
}
You would be wanting
var arrNewArray = new string[arrOldArray.Length, 7];
var arrNewArray = new[] {new string[7]};//array of arrays
var arrNewArray = new string[arrOldArray.Length, 7];//two-dimensional array
Using Linq:
int[][] jaggedArray2 = new int[][]
{
new int[] {1,3,5,7,9},
new int[] {0,2,4,6},
new int[] {11,22}
};
int length = jaggedArray.Sum(a => a.Length);
I don't believe what you're asking is directly possible. Because the syntax that you are using is for a jagged array, and what you are doing is effectively asking it to create a multi-dimensional array.
The syntax is confusing since it reads like what you really want is a multi-dimensional array (although I'm aware that's not the case.)
I don't believe you could store your arrays in the newly allocated array either due to a size change. You would need to build a custom copy method to move the data into the larger array.
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
How to resize multidimensional (2D) array in C#?
I have 2D array : myarray[5,6];
And my array is already full. But still, i want to add some more elements in it.
So , how to extend the size of an array?
OR
how to declare dynamic 2D array? (Sorry for asking silly question :P)
What you want is a List of Lists.
List<List<int>> data = new List<List<int>>();
for(int i = 0; i < rowsToAdd; i++)
{
List<int> newRow = new List<int>();
for(int j = 0; j < columnsToAdd; j++)
{
newRow.Add(j);
}
data.Add(newRow);
}
Then to add a new row:
List<int> nextRow = new List<int>(){0,1,2,3};
data.Add(nextRow);
You can use Array.Resize():
var arr = new int[10];
Array.Resize(ref arr, arr.Length * 2); // doubles the array size
Update
Sorry, I just missed 2D:
Take a look at this question.
I fear you are asking for the solution of the wrong problem.
You should not (in most cases) resize your array by hand. Use and generic list (or a generic list of generic lists) as already suggested here
Please, read this rant: Arrays considered somewhat harmful
Consider using generic lists as already suggested by others.
You have to create a new array if you need to extend the size. If you look at the right side, you can see an answer.