Reputation: 11
I'm doing data involving arrays in C#, when I use the foreach loop it gave me an message
cannot convert type char to string
int[,] tel = new int[4, 8];
tel[0, 0] = 398;
tel[0, 1] = 3333;
tel[0, 2] = 2883;
tel[0, 3] = 17698;
tel[1, 0] = 1762;
tel[1, 1] = 176925;
tel[1, 2] = 398722;
tel[2, 0] = 38870;
tel[3, 1] = 30439;
foreach (string t in tel.ToString())
{
Console.WriteLine(tel +" " +"is calling");
Console.ReadKey();
}
Upvotes: 0
Views: 11308
Reputation: 32266
That is becuase when you foreach
over a string
each value will be a char
, but you are trying to cast them to string
.
foreach(string t in tel.ToString())
But it's unlikely that you want to foreach
on tel.ToString()
as the will return the name of the type of tel
(System.Int32[,]
). Instead you probably want to iterate all the values in tel
for(int i=0; i<4; i++)
{
for(int j=0; j<8; j++)
{
Console.WriteLine(tel[i,j] +" is calling");
Console.ReadKey();
}
}
Or
foreach(int t in tel)
{
Console.WriteLine(t +" is calling");
Console.ReadKey();
}
Note that some of the values will be zero since you do not assign values to all the positions in the tel
array.
Upvotes: 3
Reputation: 1079
Iterate over the values in the array like this:
int rowLength = tel.GetLength(0);
int colLength = tel.GetLength(1);
for (int i = 0; i < rowLength; i++)
{
for (int j = 0; j < colLength; j++)
{
Console.WriteLine(tel[i, j]+" is calling");
}
}
Console.ReadLine();
Upvotes: 0