简体   繁体   中英

1 dimension array to 2 dimension array

I am trying to create an application that reads a textfile with is formated like this :

Outremont,3456,4370,15342,546
St-Leonard,6098,12765,10876,1024  
Chapleau,6087,6087,6087,6087

It basically contains on each line a town name and 4 values that represent number of votes for a political party.

What i need to do is to retrieve each value from each line and then add them together.

Example: I would retrieve the 2nd value from the first line(3457) and the 2nd value from the second line (6098) and add them together.

So far I know how to split one line into an array so I can get. I am using a streamreader to retrieve the information of the textfile and then I am splitting one line using the Split method.

So far my code looks like this

public partial class Form1 : Form
    {

        string[] mots;

private void btnLire_Click(object sender, EventArgs e)
    {

        StreamReader reader = new StreamReader(txtCheminAccess.Text);
        while (!reader.EndOfStream)
        {
            string sVal = reader.ReadLine();
            if (sVal.Length > 0)
            {
                mots = sVal.Split(',');

            }
        }
    }

Of course I can't retrieve every line but just one at a time. In this case, if you refer yourself to the textfile

Outremont,3456,4370,15342,546
St-Leonard,6098,12765,10876,1024
Chapleau,6087,6087,6087,6087 

My array called mots will only contains the last line. Chapleau,6087,6087,6087,6087

How can I put this 1 dimensional array into a 2 dimensional array so it looks like Array[textfile Lines,mots] ?

If all you want is the totals, then there's no need to create a two dimensional array. Create one array of totals, and then add each item as you read it. Like this:

int totals[] = new totals[4];
foreach (var sVal in File.ReadLines(txtCheminAccess.Text))
{
    if (sVal.Length > 0)
    {
        mots = sVal.Split(',');
        for (int i = 1; i < 5 && i < sVal.Length; ++i)
        {
            int val;
            if (int.TryParse(sVal[i], out val))
            {
                totals[i-1] += val;
            }
        }
    }
}

File.ReadLines reads the file line-by-line. It's very convenient shorthand for the StreamReader loop that you created.

After reading the line, it's split the way you split it, and then the code goes through the split array to parse the integers and add them to the totals.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM