[英]Loading and parsing data from file into array
I am trying to load data from a DAT file into an array.我正在尝试将数据从 DAT 文件加载到数组中。
My data is composed of multiple rows in the following format:我的数据由以下格式的多行组成:
param_1::param_2::value
I want to read this data in and convert it to a 2D-array (or other suitable format), so I will have:我想读取这些数据并将其转换为二维数组(或其他合适的格式),所以我将有:
myData[param_1,param_2]=value
Currently I am trying to read in the file into a an array of strings using StreamReader, but do not know how to convert the data from strings into the format I need.目前我正在尝试使用 StreamReader 将文件读入一个字符串数组,但不知道如何将数据从字符串转换为我需要的格式。
This is the read part I'm using right now.这是我现在正在使用的阅读部分。 What do I need to do to parse the data correctly?我需要做什么才能正确解析数据?
StreamReader reader = new StreamReader("file.dat");
string strAllFile = reader.ReadToEnd().Replace("\r\n", "\n").Replace("\n\r", "\n");
string[] arrLines = strAllFile.Split(new char[] { '\n' });
Thanks for your help!谢谢你的帮助!
You could do something like this, this Linq
statement returns collection of param1, param2, value
from each line in file.你可以做这样的事情,这个Linq
语句从文件中的每一行返回param1, param2, value
集合。
var dataList = File.ReadAllLines("file.dat") // Read lines
.Select(l=> l.Split(new string[] { "::" }, StringSplitOptions.None)) // split each line
.Select(l=> new
{
param1 = l[0],
param2 = l]1],
value = l[2]
})
.ToList();
Now you can iterate list using现在您可以使用迭代列表
foreach(var item in dataList)
{
// logic here.
myData[item.param1,item.param2]=item.value
}
if number of row and columns of myData
is known, you can simply write your function like this:如果已知myData
的行数和列数,您可以简单地编写您的函数,如下所示:
public void parseString(string[] lines)
{
int[,] myData = new int[100, 100];
foreach (string s in lines)
{
string[] data = s.Split("::");
int x = Convert.ToInt32(data[0]);
int y = Convert.ToInt32(data[1]);
int value = Convert.ToInt32(data[2]);
myData[x, y] = value;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.