简体   繁体   中英

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

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 convert it in to a int array but it gives an error.

The contents of the text file:

146429,143689,144380,141523,139572,136930,133714,130011,125843,121110,115974,110363,104367,97909,91245,84218,77008,69626,62058,54445,46942,39436,32146,24932,18359,12601,9039,9776,13638,18314,23221,27728,32142,35941,39577,42657,45692,48180

My code:

while ((line = sr.ReadLine()) != null)
{
    string[] values = line.Split(new string[] { " , " }, StringSplitOptions.None); 

    for (int i = 0; i < values.Length; i++)
    {
        // Console.WriteLine(values[i]);
        valArr[LineCount][i] = Convert.ToInt64(values[i]); // error
    }

    LineCount++;
}

I think this is what you are after:

    static void Main(string[] args)
    {
        var sr = new StreamReader(@"d:\test.txt");
        long[] data = ExtractData(sr).ToArray();
    }

    private static IEnumerable<long> ExtractData(StreamReader sr)
    {
        string line;
        while ((line = sr.ReadLine()) != null)
        {
            var items = line.Split(',');
            foreach (var item in items)
            {
                yield return Convert.ToInt64(item);
            }
        }
    }

With my test file (d:\\test.txt) holding:

1,2,3,4,5
1,2,3,4

I get the array containing:

1,2,3,4,5,1,2,3,4

EDIT

As Monroe pointed out, I missed the fact you wanted an array of arrays. Here's another version that gives such a jagged array. Still keeping yield in though ;)

    static void Main(string[] args)
    {
        var sr = new StreamReader(@"d:\test.txt");
        var data = ExtractData(sr).ToArray();
    }

    private static IEnumerable<long[]> ExtractData(StreamReader sr)
    {
        string line;
        while ((line = sr.ReadLine()) != null)
        {
            yield return line.Split(',').Select(i => Convert.ToInt64(i)).ToArray();
        }
    }

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

var lineArray = new List<List<Int64>>();

foreach (var lineString in File.ReadAllLines("path"))
{
    var line = new List<Int64>();
    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();  

It should be something nearly to:

int yourIntArray = 
    new List<string>(RealAllText(fileName)
    .Split(new char[] {',', '\r', '\n', ' '},
    stringSplitOptions.RemoveEmptyEntries))
    .ConvertAll<int>(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.

I think this is what you want to do. Only thing is that your vallArr should be a two dimensional array that can keep all values. Something like var valArr = new Int64[x, y];

        while ((line = sr.ReadLine()) != null)
        {
            string[] values = line.Split(new string[] { " , " }, StringSplitOptions.None);

            for (int i = 0; i < values.Length; i++)
            {
                valArr[LineCount, i] = Int64.Parse(values[i]);
            }
            LineCount++;
        }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM