从读取文本文件的每一行到双打的数组或整数使用C# [英] Reading each row from text file into an array of doubles or integer using C#
问题描述
假如我有数据的文本文件类似下面,我想读的第一行和内容存储在一个阵列。阅读第二行和存储在第二阵列等。我将在阵列上以后进行一些操作。你能不能帮我在C#这样做吗?
Suppose I have a text file with data like below, I want to read first row and store the elements in one array. Read the second row and store in second array and so on. I will be making some manipulations on the array later on. Can you help me to do this in C#?
输入文本文件:
5,7,3,6,9,8,3,5,7
5,7,3,6,9,8,3,5,7
5,6,8,3,4,5
5,6,8,3,4,5
6,4,3,2,65,8,6,3,3,5,7,4
6,4,3,2,65,8,6,3,3,5,7,4
4,5,6,78,9,4,2,5,6
4,5,6,78,9,4,2,5,6
的code我想的是:的
The Code I am trying out is:
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数组的第一行。有没有一种方法,以循环为所有的行?的
If I use the above technique, I can get the first line in array val. Is there a way to loop it for all the rows?
推荐答案
我想通了。感谢所有为您的时间!
I figured it out. Thanks all for your time!
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);
}
});
这篇关于从读取文本文件的每一行到双打的数组或整数使用C#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!