How to read a text file and add the data to a int array in C#?

后端 未结 4 1371
深忆病人
深忆病人 2021-01-27 06:13

I\'m trying to read a text file which contains numbers separated by a comma. When I read using File.Readline() I get it to a string[]. I need to conver

4条回答
  •  抹茶落季
    2021-01-27 06:41

    Using List can help you, and use StringSplitOptions.RemoveEmptyEntries to prevent null exception in Convert.ToInt64

    var lineArray = new List>();
    
    foreach (var lineString in File.ReadAllLines("path"))
    {
        var line = new List();
        string[] values = lineString.Split(new[] { ',', ' ' },  
                                           StringSplitOptions.RemoveEmptyEntries);
        line.AddRange(values.Select(t => Convert.ToInt64(t)));
        lineArray.Add(line);
    }
    

    and using it:

    // Array of numbers for specific line
    var resultArray = lineArray[lineNumber].ToArray();  
    

提交回复
热议问题