1

假设我有一个包含如下数据的文本文件,我想读取第一行并将元素存储在一个数组中。读取第二行并存储在第二个数组中,依此类推。稍后我将对数组进行一些操作。你能帮我在 C# 中做到这一点吗?

输入文本文件:

5,7,3,6,9,8,3,5,7

5,6,8,3,4,5

6,4,3,2,65,8,6,3,3,5,7,4

4,5,6,78,9,4,2,5,6

我正在尝试的代码是:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;

namespace ReadFile
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        static void Main(string[] args)
        {
            TextReader tr = new StreamReader("Data.txt");
            // write a line of text to the file
            string word = tr.ReadLine();
            //now split this line into words
            string[] val = word.Split(new Char[] { ',' });
        }
    }

}

如果我使用上述技术,我可以得到数组 val 中的第一行。有没有办法为所有行循环它?

4

7 回答 7

4

File.ReadAllLines将帮助您从文件中读取所有行作为字符串数组。
String.Split将帮助您将线条分割成几部分。
Int.Parse将帮助您将字符串转换为 int(double 具有类似的方法)。

于 2012-07-17T06:50:43.530 回答
1

好的,既然您是初学者,我建议您集中注意力。首先,您的消费者是否总是需要所有的线路,或者它可以在某个时候停止?如果是这样,使用yield策略将结果一一返回。在任何情况下,您都可以使用StreamReader逐行读取,并在使用分隔符拆分字符串后使用double.TryParse(...)int.TryParse()。请注意分隔符可以更改的事实,因此请以某种可配置性使用它,并且在双精度的情况下,确保您的代码即使在配置了不同小数点的机器上也能正常工作。如果您确定您的 csv 始终用作小数点分隔符,请指定'.'

double.TryParse("",System.Globalization.CultureInfo.InvariantCulture);
于 2012-07-17T07:02:57.373 回答
0

我分两部分介绍了以下代码,只是为了分步向您展示。

第 1 节

这段代码只是为了表明您只需要遍历所有行并将每行的字符串数字存储在 List 中。

第 1 节

static void Main(string[] args)
{
     List<string[]> allLines = new List<string[]>();

     TextReader tr = new StreamReader("Data.txt");
     string word = tr.ReadLine();

     // write a line of text to the file
     while ( word !=  null ) {

         //now split this line into words
         string[] vals = word.Split(new Char[] { ',' });

         //Add this line into allLines
         allLines.Add(vals);

         //Now read the next line
         word = tr.ReadLine();
     }
}

第 2 节

本节将为您提供结果int

static void Main(string[] args)
{
     //A list of arrays of integers
     //A single array will have numbers from a single line
     List<int[]> allNumbers = new List<int[]>();

     TextReader tr = new StreamReader("Data.txt");
     string word = tr.ReadLine();

     // write a line of text to the file
     while ( word !=  null ) {

         //now split this line into words
         string[] vals = word.Split(new Char[] { ',' });
         int[] intVals = new int[vals.Length];

         for ( int i = 0; i < vals.Length; i++) {
             Int32.TryParse(vals[i], out intVals[i]);
         }

         //Add this array of integers into allNumbers
         allNumbers.Add(intVals);

         //Now read the next line
         word = tr.ReadLine();
     }
}

注意:我没有编译或测试上面的代码。

于 2012-07-17T07:46:09.690 回答
0

看到这行代码:

List<List<int>> numbers = new List<List<int>>();
foreach (string line in File.ReadAllLines(""))
{
    var list = new List<int>();
    foreach (string s in line.Split(new[]{',', ' '}, 
                                    StringSplitOptions.RemoveEmptyEntries))
    {
        int i;
        if(int.TryParse(s, out i))
        {
            list.Add(i);
        }
    }
    numbers.Add(list);
}

var specialNumber = numbers[3][4];        // gives line 3 number 4
var specialLine = numbers[2].ToArray();   //  gives an array of numbers of line 2

描述: 我使用了这个有用的 Generic:

  • List: 表示可以通过索引访问的对象的强类型列表

以及这些有用的类:

  • File.ReadAllLines: 打开一个文本文件,将文件的所有行读入一个字符串数组
  • String.Split:返回一个字符串数组,其中包含此实例中由指定字符串或 Unicode 字符数组的元素分隔的子字符串。
  • Int.TryParse:将数字的字符串表示形式转换为其等效的 32 位有符号整数。
于 2012-07-17T06:48:15.353 回答
0

我想到了。谢谢大家的时间!

private void ReadFile()
    {
        var lines = File.ReadLines("Data.csv");
        var numbers = new List<List<double>>();
        var separators = new[] { ',', ' ' };
        /*System.Threading.Tasks.*/
        Parallel.ForEach(lines, line =>
        {
            var list = new List<double>();
            foreach (var s in line.Split(separators, StringSplitOptions.RemoveEmptyEntries))
            {
                double i;

                if (double.TryParse(s, out i))
                {
                    list.Add(i);
                }
            }

            lock (numbers)
            {
                numbers.Add(list);
            }
        });
于 2012-08-03T06:56:48.123 回答
0

尝试这个

using System;
using System.Collections.Generic;
using System.Linq;
using System.Xml;
using System.IO;
using System.Xml.Linq;
using System.Diagnostics;

namespace ConsoleApplication5
{
    class Program
    {
        static void Main(string[] args)
        {

            List<int[]> arrays = new List<int[]>();

            int counter = 0;
            string line;

            // Read the file
            System.IO.StreamReader file =
               new System.IO.StreamReader("c:\\temp\\test.txt");
            while ((line = file.ReadLine()) != null)
            {
                // split the line into a string array on , separator
                string[] splitLine = line.ToString().Split(',');

                // if our split isnt null and has a positive length
                if (splitLine != null && splitLine.Length > 0)
                {

                    // create a lineArray the same size as our new string[]
                    int[] lineArray = new int[splitLine.Length];

                    int posCounter = 0;

                    foreach (string splitValue in splitLine)
                    {
                        // loop through each value in the split, try and convert
                        // it into an int and push it into the array
                        try
                        {
                            lineArray[posCounter] = Int32.Parse(splitValue);
                        }
                        catch { }
                        posCounter++;
                    }

                    // if our lineArray has a positive length then at it to our
                    // list of arrays for processing later.
                    if (lineArray.Length > 0)
                    {
                        arrays.Add(lineArray);
                    }
                }
                counter++;
            }

            file.Close();

            // go through the List<int[]> and print to screen
            foreach (int[] row in arrays)
            {
                foreach (int rowCol in row)
                {
                    Console.Write(rowCol + ",");
                }
                Console.WriteLine();
            }

            // Suspend the screen.
            Console.ReadLine();
        }
    }
}
于 2012-07-17T06:53:39.410 回答
0

大致像这样的东西会起作用:

StreamReader reader = new (File.OpenRead(@"YourFile.txt"));
List<string> LstIntegers = new List<string>();

            while (!reader.EndOfStream)
            {
                var line = reader.ReadLine();
                //values is actually a string array.
                var values = line.Split(',');
                //add the entire array fetched into string List
        LstIntegers.AddRange(values);   
            }
          // important to close the reader. You can also use using statement for reader. It 
          // will close the reader automatically when reading finishes.
            reader.Close();

   // You can then further manipulate it like below, you can also use int.Parse or int.TryParse:
   foreach (var v in LstIntegers)
   {
      // use int.TryParse if there is a chance that a non-int is read.
      int someNum = Convert.ToInt32(v);

   }
于 2012-07-17T07:02:02.060 回答