I am trying to read a file into a global array, loop through the array and identify each string to it’s corresponding amount, and then find the sums in their own groups. and divide those groups each by their own unique number.
The text file that I am reading in:
Name,50
Name,40
DifferentName,50
AnotherName,10
Name,60
What would be the easiest way to split the lines at the commas, and make the numbers correspond to their specific names, not knowing which order they will be in?
Here is the code I am using so far..although right now it is just the open file dialog, I am putting this here as a constructive reference.
string strFileName;
private void btnReadInFile_Click(object sender, EventArgs e)
{
//select the file
OpenFileDialog ofdGetFile = new OpenFileDialog();
if (ofdGetFile.ShowDialog() == DialogResult.Cancel)
{
//cancel
MessageBox.Show("User Canceled");
return;
}
else
{
//open the file
StreamReader myStreamReader;
strFileName = ofdGetFile.FileName;
FileStream input = new FileStream(strFileName, FileMode.Open, FileAccess.Read);
myStreamReader = new StreamReader(input);
// other
MessageBox.Show("Reading Complete", "Done!", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
}
private void btnShowGrade_Click(object sender, EventArgs e)
{
if (strFileName != null)
{
String[][] nameSums = System.IO.File.ReadLines(strFileName)
.Select(l => l.Split(',')) // split the line
.GroupBy(arr => arr[0]) // group by name
.Select(grp => new String[]{
grp.Key,
grp.Sum(arr => int.Parse(arr[1])).ToString()})
.ToArray();
}
else
{
MessageBox.Show("You need to read in a file first.");
}
}
}
I feel like there has to be a better way to do this.
Thank you all so much for your help thus far! I am sure that the only reason this problem hasn’t been resolved is my lack of communication skills.
Note this will be a staggered array, not a 2 dimensional one. To create a 2 dimensional one, you could use