I want to resize my array dynamic. Everything would be ok, but in example I find someone use Array.Resize() to resize one dimension array, but I want to have possibility create jagged array. I read from file line, in which it could be some numbers separate by space - therefore i need jagged array created dynamic. It's my class when i use it, but my array don't resize :(
class Program
{
int[][] nodesMatrix = null;
private void ReadFromFile(string fileName)
{
string line;
int nodesNr;
if(File.Exists(fileName) )
{
StreamReader fileReader = null;
try
{
fileReader = new StreamReader(fileName);
int lineNr = 0;
while ((line = fileReader.ReadLine()) != null)
{
int connectionsNr = 0;
if (lineNr==0)开发者_C百科
{
nodesNr = Convert.ToInt32(line);
nodesMatrix = new int[nodesNr][];
for (int i = 0; i < nodesNr;i++ )
{
nodesMatrix[i] = new int[1];
}
}
else
{
string tmpNumber = null;
foreach (char sign in line)
{
if (sign != ' ')
{
tmpNumber += sign;
}
if (sign == ' ')
{
if (tmpNumber != null)
{
//nodesMatrix[lineNr] = new int[connectionsNr+1];
nodesMatrix[lineNr][connectionsNr] = Convert.ToInt32(tmpNumber);
connectionsNr++;
Array.Resize<int>(ref nodesMatrix[lineNr], connectionsNr); //here i try to resize array
}
tmpNumber = null;
}
}
}
lineNr++;
}
}
finally
{
if (fileReader != null)
fileReader.Close();
}
}
Maybe You know how to do it ?
Maybe I'm not understanding your use case but it seems to me that if you have a data structure that you know will need to be resized, that it's better to use a List or related structure, rather than an array. You can always convert the list back to an array at the end via the .ToArray() extension added by linq.
Likewise, if you use generics, you can ensure that you have a strongly typed, multi-dimensional list. You could likewise use a pair of lists internally, and create your own class that wraps them both.
I don't understand why you want to use an array here rather than the automatically resizing collections, however have a look at this link on MSDN that shows the "resizing" and use of jagged arrays in C#:
- Jagged Arrays (C# Programming Guide)
精彩评论