Address a single row of a 2-dimensional array? - c#

Is there any way in c# to address a single row of a 2-dimensional array?
I want to be able to pass one-dimension of a 2 dimensional array as a parameter and sometimes I want to pass the whole 2-dimentional array.

You can use jagged arrays.
Example based on the code in Jagged Arrays (C# Programming Guide):
int[][] jaggedArray = new int[3][];
jaggedArray[0] = new int[5];
jaggedArray[1] = new int[4];
jaggedArray[2] = new int[2];
// To pass the whole thing, use jaggedArray
// To pass one of the inner arrays, use jaggedArray[index]

Related

Why can't I create a multidimensional array of arrays?

My program involves a 2-dimensional board: Square[width,height]. Each Square contains a collection of Pieces.
In the presentation layer, I want to only present the collection of Pieces in each Square and represent each Piece with its string Name. I.e. string[][width,height].
Declaring string[][,] compiles with no problem but I can't initialize the variable:
string[][,] multiArrayOfArrays; //No problemo
multiArrayOfArrays = new string[][8,8]; //Generates errors
The following errors are generated for the second line:
CS1586 Array creation must have array size or array initializer
CS0178 Invalid rank specifier: expected ',' or ']' ModChess
CS0178 Invalid rank specifier: expected ',' or ']' ModChess
I'm currently using List<string>[,] as a workaround but the errors vex me. Why can I successfully declare a string[][,] but not initialize it?
Note: Using VS Community 16.0.4, C# 7.3.
string[][,] multiArrayOfArrays; //No problemo
Here you just declare variable of specific type.
multiArrayOfArrays = new string[][8,8]; //Generates errors
And here you actually create new object of specific type. It generates errors because this is invalid syntax for multidimentional array initialization.
You need to specify size for first dimension [] and then initialize each element of that array with string[,].
Think of it as array of arrays:
string[][,] multiArrayOfArrays; //No problemo
multiArrayOfArrays = new string[5][,];//create 5 elements of string[,] array
for (int i = 0; i < multiArrayOfArrays.Length; ++i)
{
multiArrayOfArrays[i] = new string[8,8];//actually fill elements with string[8,8]
}
or
string[][,] multiArrayOfArrays; //No problemo
multiArrayOfArrays = new string[][,]
{
new string[8,8],
new string[8,8],
new string[8,8],
};
Probably you want a string[,][] a.
string[,][] a = new string[3, 4][];
a[0, 0] = new string[10];
a[0, 1] = new string[4];
a[1, 0] = new string[6];
string s = a[0, 0][2];
You have a special case of a jagged array, where the first array is 2-dimensional. It contains one-dimensional arrays of different sizes as elements.
The ordering of the array brackets might seem wrong, as the element type is usually on the left side of the brackets; however, if you think about on how you want to access elements, then it makes sense. First, you want to specify the 2 coordinates of the 2-dimensional board, then the single index of the pieces collection.
According to Jagged Arrays (C# Programming Guide), int[][,] jaggedArray4 = new int[3][,] "... is a declaration and initialization of a single-dimensional jagged array that contains three two-dimensional array elements of different sizes."

Get one dimensionial array from a mutlidimensional array in c#

I have a two dimensional array like this:
decimal[,] dataArray;
dataArray = new decimal[10, 20];
How can I get an onedimesional array that contains the values from one particular column?
Thanks.
There is no built-in API for slicing multidimensional arrays. Write a loop that goes through all rows, and harvests a specific column into a result array, or use LINQ to "fold" the loop:
var col = Enumerable.Range(0, 20).Select(r=>dataArray[3, r]).ToArray();

Maximum number of elements in a 2D array

I need to make an 2d array, but c# won't let me and says that it is too big, any ideas how to make it work?
int[,] arrayName = new int[37153,18366];
The max theoretical size of an int array is 2147483647 i.e. int[] array = new int[2147483647] but the probleming you're having here is that the computer runs of out memory.
Read this for explanation and tips on how to solve this:
OutOfMemoryException on declaration of Large Array
If you are not using the complete range of the array (which is in your case 2,7GB of RAM), you could use a Dictionary.
https://msdn.microsoft.com/de-de/library/xfhwa508(v=vs.110).aspx
Alternative: Create a [][] Array. In this case you must initialize each row.
But you can access each cell easy with arrayName[row][col].
int[][] arrayName = new int[37153][];
for(int i=0; i<arrayName.Length; i++)
arrayName[i] = new int[18366];

File.ReadAllLines method on 2D array

I am about to create a media player app, which will handle multiple playlists with of course, multiple songs. I've created an array of strings for the playlist names, they are stored in a text file. I load them with the File.ReadAllLines method like this:
1darray = File.ReadAllLines("textfilename.txt");
Every playlist has his own ID, I have a variable which stores the number of playlists.
I would like to read the Path of the songs with the same method, but it needs a 2D Array
2Darray[playlistID, songID]
As with the first method I didn't have to specify each element of the array, I will need now to specify the playlistID, and let the File.ReadAllLines method to fill the songID elements, but it doesn`t work like this:
2Darray[playlistID] = File.ReadAllLines("textfilename.txt");
it says Wrong number of indices inside []; expected 2.
How to deal with it?
Hope you understand my bad english!
Scan directory for playlist files: Directory class
Then enumerate the found files:
foreach (string filename in filenames)
{
// ...
}
Use each filename as the playlist ID:
Dictionary<string, string[]> playlists;
Collect each file's lines in the dictionary:
playlists.Add(filename, File.ReadAllLines(filename));
Get a specific playlist's entry (here, 4th of "dupestep.pl"):
playlists["dupestep.pl"][3] // index 3 is the 4th, because it's zero-based
From here on you should be able to implement whatever you need.
To abstract the list of playlists you can extract the list of keys to translate indices to filenames and viceversa:
playlists.Keys
While lots of people have suggested alternative solutions to your problem, nobody has yet explained what the original error means. What you need to understand is that C# makes a distinction between so-called jagged arrays and multidimensional arrays.
A jagged array is essentially an array of arrays. Declaring one looks like this:
int[][] jaggedArray = new int[4][];
This creates an array with four elements, and each of those four elements can be any array of int, of any size. This is why such arrays are called "jagged": some elements can be bigger than others. You can imagine it looking something like this:
[0, 1]
[5, 3, 2, 1]
[]
[9, 8, 7, 6, 5, 4, 2]
Note the jagged edge.
In keeping with the declaration, jagged arrays are accessed like this:
int[] element = jaggedArray[1];
int value = jaggedArray[1][2]; // equivalent to element[2]
Multidimensional arrays behave differently. A multidimensional array is declared like this:
int[,] multidimArray = new int[4, 4];
Unlike a jagged array, multidimensional arrays specify the size of both dimensions. All of the elements in such an array are of the same size. You can imagine it looking more like this:
[0, 1, 2, 3,
5, 4, 3, 2,
0, 0, 0, 0,
9, 8, 7, 4]
Multidimensional arrays must also be accessed somewhat differently. Unlike jagged arrays, which are effectively arrays of arrays, a multidimensional array is treated as a single, cohesive unit. Doing this:
int[] element = multidimArray[3];
...doesn't make any sense, because a multidimensional array isn't made up of smaller arrays. You can only access individual values within the array, and you do so like this:
int value = multidimArray[3, 2];
Note that you have to specify both indices within a single [] operator. These are the "coordinates" of the value you want, so to speak.
And this is the source of your error. You had a multidimensional array and you were attempting to access its individual array elements, which doesn't make any sense. To do what you were originally trying to do, you need to use a jagged array.
So basically you can map all playlists with their respective songs with a Dictionary>. Ofcourse this can be done better with classes and relations, however to keep it simple we will use the first example:
//get all playlists
string[] playLists = File.ReadAllLines("playLists.txt");
//storage
Dictionary<string, List<string>> playListsToSongsMap = new Dictionary<string, List<string>>();
//iterate the readed playlists
foreach (string playlist in playLists)
{
if (!playListsToSongsMap.ContainsKey(playlist))
{
playListsToSongsMap[playlist] = new List<string>();
}
//add songs to each playlist
playListsToSongsMap[playlist].AddRange(File.ReadLines("playListWithsongsPath"));
}
//get all playlits
List<string> allPlayLists = playListsToSongsMap.Keys.ToList();
//get all songs in a playlist
List<string> songsInPlaylist = playListsToSongsMap[allPlayLists[0]];

How to pass part of a two-dimensional array as parameter to a function?

I've got a two-dimensional array like this:
double[,] results = new double[100,100];
I'd like to pass every one dimensional part of the array to a function as a paremeter.
for (int i = 0; i < 100; i++){
cool_function (results[???], 10);
}
How do I do this in C#?
source
Jagged arrays are arrays of arrays. The elements of a jagged array are other arrays.
Declaring Jagged Arrays
Declaration of a jagged array involves two brackets. For example, the following code snippet declares a jagged array that has three items of an array.
int[][] intJaggedArray = new int[3][];
The following code snippet declares a jagged array that has two items of an array.
string[][] stringJaggedArray = new string[2][];
Initializing Jagged Arrays
Before a jagged array can be used, its items must be initialized. The following code snippet initializes a jagged array; the first item with an array of integers that has two integers, second item with an array of integers that has 4 integers, and a third item with an array of integers that has 6 integers.
// Initializing jagged arrays
intJaggedArray[0] = new int[2];
intJaggedArray[1] = new int[4];
intJaggedArray[2] = new int[6];
We can also initialize a jagged array's items by providing the values of the array's items. The following code snippet initializes item an array's items directly during the declaration.
// Initializing jagged arrays
intJaggedArray[0] = new int[2]{2, 12};
intJaggedArray[1] = new int[4]{4, 14, 24, 34};
intJaggedArray[2] = new int[6] {6, 16, 26, 36, 46, 56 };
You can't do it without copying the corresponding part of the array.
Otherwise, you can use a double[][]. To initialize:
double[][] results = new double[100][];
for(int i = 0; i < 100; i++)
results[i] = new double[100];
You could do this by using a jagged array Type[][] instead of Type[,]. In this case you can just pass array[index]. Otherwise you will have to either pass the two-dimensional array together with the index of the subarray of interest and perform the indexing in the called method or create a copy of the subarray of interest.
If you mean for an array myarray[x][y] that you want to call a function for x arrays of size y then all you need is the following code:
int i;
for (i = 0; i < 100; i++)
{
cool_function(array[i], 10);
}

Categories