假设我有一个包含如下数据的文本文件,我想读取第一行并将元素存储在一个数组中。读取第二行并存储在第二个数组中,依此类推。稍后我将对阵列进行一些操作。你能帮我用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中的第一行。有没有办法为所有行循环?
答案 0 :(得分:4)
File.ReadAllLines将帮助您从文件中读取所有行作为字符串数组 String.Split会帮助你分割成一条线 Int.Parse将帮助您将字符串转换为int(double具有类似的方法)。
答案 1 :(得分:1)
好的,既然你是初学者我的建议是关注什么聚焦你的注意力。
首先,您的消费者是否总是需要所有线路,还是可以在某些时候停止?如果是这样,请使用yield策略逐个返回结果。在任何情况下,您都可以使用StreamReader逐行阅读,并在double.TryParse(...)之后使用分隔符int.TryParse()或splitting the string。请注意分隔符可以更改的事实,因此请使用某种可配置性,如果是double,请确保您的代码即使在配置了不同小数点的计算机中也能正常工作。如果您确定csv alwais使用'.'
作为小数点分隔符,请指定
double.TryParse("",System.Globalization.CultureInfo.InvariantCulture);
答案 2 :(得分: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位有符号整数。答案 3 :(得分: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();
}
}
}
答案 4 :(得分: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);
}
答案 5 :(得分:0)
我在两个部分中提供了以下代码,只是为了向您展示步骤。
此代码只是为了表明您只需要遍历所有行并存储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();
}
}
此部分将为您提供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();
}
}
注意:我没有编译或测试上面的代码。
答案 6 :(得分: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);
}
});