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

后端 未结 4 1527
深忆病人
深忆病人 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:33

    It should be something nearly to:

    int yourIntArray = 
        new List(RealAllText(fileName)
        .Split(new char[] {',', '\r', '\n', ' '},
        stringSplitOptions.RemoveEmptyEntries))
        .ConvertAll(s => int.Parse(s))
        .ToArray();
    

    Of course, for more robustness, int.Parse should be replaced with some method that will handle errors in numbers, and so on...

    EDIT:

    Oh, I just saw that you have lines that are another index to your array... Well then, this code should be modified in that case, but I'll leave that to you.

提交回复
热议问题