convert two dimensional string array to two dimensional int array - c#

I'm trying to convert a two dimensional string array to a two dimensional int array:
int[][] inner = new int[4][];
string[][] arr = new string[4][]
{
new string[] {"11"},
new string[] {"12"},
new string[] {"21"},
new string[] {"22"}
};
for (int i = 0; i < arr.Length; i++)
{
string name = string.Join(".", arr[i]);
for (int j = 0; j < name.Length; j++)
{
inner[i][j] = Convert.ToInt32(name.Substring(j,1));
}
}
But I'm getting the following exception:
Object reference not set to an instance of an object
at:
inner[i][j] = Convert.ToInt32(name.Substring(j,1));

Change the declaration of your "inner" variable to
int[,] inner = new int[4,2];

Related

How can I split data present in an array into another array.?

Basically, I am trying to split an array and want to pass its value into another array.
But, I am not able to do it.It is givin an error:
Cannot implicitly convert type String[] to string"
StreamReader EmployeeFile = new StreamReader(#"C:\Users\user\Desktop\FoodDeliverySystem\Employee_details.txt");
String ReadEmployeeData = EmployeeFile.ReadToEnd();
String[] ReadEmployeeDataByLine = ReadEmployeeData.Split(';');
for (int k = 0; k < 5; k++)
{
for (int l = 0; l < 5; l++)
{
Console.WriteLine("test");
String[,] ReadEmployeeDataByLineByCategorie = new string[k, l];
ReadEmployeeDataByLineByCategorie[k,l] = ReadEmployeeDataByLine[l].Split(',');
}
}
Since you can't be sure of how many of those values you're gonna have in each category of yours, you should use jagged arrays
That should do:
var readEmployeeDataByLine = new StreamReader(#"C:\pathToFile.txt").ReadToEnd().Split(';');
var readEmployeeDataByLineByCategorie = new string[readEmployeeDataByLine.Length][];
for (int i = 0; i < readEmployeeDataByLineByCategorie.Length; i++)
readEmployeeDataByLineByCategorie[i] = readEmployeeDataByLine[i].Split(',');
ReadEmployeeDataByLineByCategorie[k,l] is a string
while ReadEmployeeDataByLine[l].Split(',') is a string[]
string[] ReadEmployeeDataByLine = ReadEmployeeData.Split(';');
for(int i = 0;i< ReadEmployeeDataByLine.Length;i++)
{
string split = ReadEmployeeDataByLine[l].Split(',');
for(int j=0; j<split.Length;j++)
ReadEmployeeDataByLineByCategorie[i,j] = split[j]
}

Converting a Jagged Array to a multidimensional array [duplicate]

This question already has answers here:
Converting jagged array to 2D array C#
(4 answers)
Closed 3 years ago.
I am converting a list within a list to an int[][] using:
int[][] preConvertInts = processedList.Select(array => array.ToArray().ToArray()) as int[][];
I am returning an int[,] in my method. What is the best way to convert an int[][] to an int[,]?
Edit: method
public static int[,] GetIntArrayInts(string dataString){
string data = dataString;
data = data.Replace(Environment.NewLine, "\n");
List<List<int>> processedList = new List<List<int>>();
string[] rows = data.Split('\n');
foreach (string row in rows){
string[] columns = row.Split(',');
List<int> ints = new List<int>();
foreach (string column in columns){
if (int.TryParse(column, out int tileGid)) ints.Add(tileGid);
}
processedList.Add(ints);
}
int[][] preConvertInts = processedList.Select(array => array.ToArray().ToArray()) as int[][];
int[,] processedIntArray = new int[preConvertInts[0].Length, preConvertInts[1].Length];
for (int i = 0; i < preConvertInts.Length; i++){
int[] intArray = preConvertInts[i];
for (int j = 0; j < intArray.Length; j++){
processedIntArray[i, j] = preConvertInts[i][j];
}
}
return processedIntArray;
}
What is the best way to convert an int[][] to an int[,]?
it is the one that is described in this post. Yours will actually also work if all sub-arrays have the same Length. But to cite you:
Unfortunately, my array is not rectangular. – Luna
Then it would not make much sense to try to convert it. Unless you loose values or you add values to make the dimensions of all sub arrays equal.
But your problem in the code is not this conversion but this one:
I am converting a list within a list to an int[][] using:
int[][] preConvertInts = processedList.Select(array => array.ToArray().ToArray()) as int[][];
This is wrong. You will get null for preConvertInts! if you check the return value of the Select call:
You can see that it returns IEnumerable<int[]> and not int[][]. Casting it with as int[][]; does not work and masks only the fact that the 2 types are different from the compiler. What you do there is to convert each sublist into an array and then convert (the already converted array) simply again into an array.
You need to make the select in the proper way:
int [][] preConvertInts = processedList.Select(x=>x.ToArray()).ToArray();
Explanation:
1) in the first step you collect all sublists and convert each one into an array: Select(x=>x.ToArray())
2) now this call returns an IEnumerable<int[]> which you need to convert again to an array:
Select(x=>x.ToArray()).ToArray();
^^
||
note the dot behind the closing parentesis of the Select call
Jagged Array
public static T[,] ToMultiArray<T>(this IList<T[]> arrays)
{
var length = arrays[0].Length;
var result = new T[arrays.Count, length];
for (var i = 0; i < arrays.Count; i++)
{
var array = arrays[i];
if (array.Length != length)
{
throw new ArgumentException("Misaligned arrays");
}
for (var j = 0; j < length; j++)
{
result[i, j] = array[j];
}
}
return result;
}
Multidimensional Array
public static T[][] ToJaggedArray<T>(this IList<T[]> arrays)
{
var result = new T[arrays.Count][];
for (var i = 0; i < arrays.Count; i++)
{
var array = arrays[i];
var length = array.Length;
result[i] = new T[length];
for (var j = 0; j < length; j++)
{
result[i][j] = array[j];
}
}
return result;
}
Usage
var preConvertInts = list.ToJaggedArray();
or
var preConvertInts = list.ToMultiArray();
Update
this IList<T[]> arrays this method is for lists which contain arrays,
to fit OP's example it should be (this IList<List<T>> arrays) – Mong
Zhu
Jagged Array
public static T[][] ToJaggedArray<T>(IList<List<T>> arrays)
{
var result = new T[arrays.Count][];
for (var i = 0; i < arrays.Count; i++)
{
var array = arrays[i];
var length = array.Count;
result[i] = new T[length];
for (var j = 0; j < length; j++)
{
result[i][j] = array[j];
}
}
return result;
}
Multidimensional Array
public static T[,] ToMultiArray<T>(IList<List<T>> arrays)
{
var length = arrays[0].Count;
var result = new T[arrays.Count, length];
for (var i = 0; i < arrays.Count; i++)
{
var array = arrays[i];
if (array.Count != length)
{
throw new ArgumentException("Misaligned arrays");
}
for (var j = 0; j < length; j++)
{
result[i, j] = array[j];
}
}
return result;
}
Note : Totally untested

How to convert List<string[]> to string[,]?

I converted a 2D array (string[,]) to the list below successfully. Now, how can I convert the List below back to a 2D array (string[,])?
List<string[]> NameList = new List<string[]>();
This is how I converted the 2D array to list:
List<string[]> NameList = new List<string[]>();
string[,] Name2DArray = new string[Rows.Count, 3];
for (int i = 0; i < Name2DArray.GetLength(0); i++)
{
string[] temp = new string[Name2DArray.GetLength(1)];
for (int n = 0; n < temp.Length; n++)
{
temp[n] = Name2DArray[i, n];
}
NameList.Add(temp);
}
Thanks all for your suggestions. I managed to fix the problem in my code. The conversion form List string[] to 2D array is now working. Below is the code:
string[,] newArray = new string[newTotalRows, 3];
for (int i = 0; i < NameList.Count; i++)
{
for (int j = 0; j < NameList[i].Length; j++)
{
newArray[i, j] = NameList[i][j];
}
}

C# Multi-dimensional Array

I'm trying to build a multi-dimensional array to store integer arrays.
Array[] TestArray = new Array[2];
for(int i = 0; i < TestArray.Length; i++)
{
TestArray[i] = new int[5];
}
How do I go about accessing the newly created members of the Array? I am not sure how to access the newly created arrays in the array although I can see that they're properly created and stored when debugging in Visual Studio.
If you want an array of integer arrays, then you should declare it as such:
int[][] testArray = new int[2][];
for(int i = 0; i < testArray.Length; i++)
{
testArray[i] = new int[5];
}
Arrays of arrays are called Jagged Arrays (in contrast to Multidimensional Arrays).
Here is how to access fourth item in the second array:
int value = ((int[]) TestArray.GetValue(1))[3];
Although you would have much less trouble working with jagged arrays:
int[][] TestArray = new int[2][];
for (int i = 0; i < TestArray.Length; i++)
{
TestArray[i] = new int[5];
}
or multidimensional arrays:
int[,] TestArray = new int[2,5];
Cast the TestArray element as an int[].
Array[] TestArray = new Array[2];
for(int i = 0; i < TestArray.Length; i++)
{
TestArray[i] = new [] { 2,3 };
}
var firstIndexOfFirstArray = ((int[])TestArray[0])[0];
T[][] is the syntax you are looking for.
int[][] test = new int[2][]; //Declaring the array of arrays.
for (int i = 0; i < test.Length; i++)
{
test[i] = new int[5]; //Instantiating a sub-arrays.
for (int x = 0; x < test[i].Length; x++)
test[i][x] = x + i; //Filling a sub-arrays.
}
foreach (var array in test) //iterating over the array of arrays.
Console.WriteLine("Array: " + string.Join(", ", array)); //using a sub-array
Console.ReadLine();
For more info: http://msdn.microsoft.com/en-us/library/2s05feca.aspx
If looking for integer array, try
int[][] testArray

Object Reference not set to instance of object

string[][] myArray = new[size][];
for(int i=0;i<2;i++){
myArray[i][0] = newValue.toString();
}
While assigning the values i get an error
I get the Object Reference not set to instance of object exception. Please help
You have created a jagged array of strings. The outermost array has been initialized to size elements, but that means there are size spaces each for a string[], each of which is currently null. You need to create the inner arrays, or create a rectangular array.
Based on the poor code, it should be something like this:
string[][] myArray = new string[size][];
for (int j = 0; j < myArray.Length; j++) {
myArray[j] = new string[3];
for (int i = 0; i < myArray[j].Length; i++) {
myArray[j][i] = newValue.ToString();
}
}
Try this
int dim1 = 2;
int dim2 = 1;
string[,] iii = new string[dim1, dim2];
for (int i = 0; i < iii.GetLength(0); i++)
{
iii[i, 0] = "myValue";
}

Categories

Resources