简体   繁体   中英

How to get data from a text file in C#

I have a text file with this info:

#ID maxSize tax
1 57247 0.0887
2 98732 0.1856
3 134928 0.2307
4 77275 0.1522
5 29240 0.0532
6 15440 0.0250
7 70820 0.1409
8 139603 0.2541
9 63718 0.1147
10 143807 0.2660

I would like to know how to get an int[] with the IDs, another int[] with the maxSize and a double[] with the taxes.

Here's a function that should do what you want. Just make sure you change the file name to be the path of your actual file.

It uses String.Split to split each line into 3 values. It then parses each of the 3 values into the types you're expecting, and adds them to the various arrays.

void ParseData( string data[], out int[] id, out int[] maxsize, out double[] tax )
{
    var lines = data.Select( line => line.Split((char[])null, StringSplitOptions.RemoveEmptyEntries) )
                    .Select( items => Tuple.Create( int.Parse(items[0]), int.Parse(items[1]), double.Parse(items[2]) ) );

    id = lines.Select( s => s.Item1 ).ToArray();
    maxsize = lines.Select( s => s.Item2 ).ToArray();
    tax = lines.Select( s => s.Item3 ).ToArray();
}

int[] ids;
int[] maxsizes;
double[] taxes;
string[] rawdata = File.ReadAllLines(@"FILENAME");

ParseData( rawdata, out ids, out maxsizes, out taxes );

Here is the code that could read file and parse it to the int[] int[] and double[]

Note I am ignoring the first line #ID maxSize tax you must include these lines before at the beginning;

using System;
using System.IO;
using System.Collections.Generic;

Code

var fileName = @"FileName";
var rawLines[] = File.ReadAllLines(fileName);
var ids = new List<int>();
var maxSizes = new List<int>();
var taxes = new List<double>();
foreach(var line in rawLines) {
    var data = line.Split(' ');
    ids.Add(Convert.ToInt32(data[0]));
    maxSizes.Add(Convert.ToInt32(data[1]));
    taxes.Add(Convert.ToDouble(data[2]));
}

// using lists
Console.WriteLine($"First Data - {ids[0]}  {maxSizes[0]}  {taxes[0]}");

Note: If your file consists of first line #ID maxSize tax then add the following code just after var data = line.Split(' ');

// safegaurd to prevent exception thrown while converting string to number types
if(!int.TryParse(data[0])) {
     continue;
}

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