2

I am trying to load data from a DAT file into an array.

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.

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!

2 Answers 2

2

You could do something like this, this Linq statement returns collection of param1, param2, value from each line in file.

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

}
Sign up to request clarification or add additional context in comments.

2 Comments

is the second .Select(...) supposed to be enclosed in the first .Select statement? There's a missing ')' somewhere...
Ahh... you are right, there was a missing bracket corrected now.
0

if number of row and columns of myData is known, you can simply write your function like this:

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;
    }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.