0

I have a text file that looks like this

Words Words 
Words Words 
Words Words 
1    34.4e+1
2    34.3e+1 
3    34.2e+1
4    34.1e+1.... // and so on  

I need to get the string number and concert it to decimal/double and then send it to an array where I can the use the array outside of the for loop to get the average via Enumerable.Chunk


decimal[] raw = new decimal[] { }; 
decimal[] rawAvgList = new decimal[] { };
decimal RawAvg = 0m;


try
{
   string bPath = aPath + "\\" + fileName.Name + "\\textfilename.txt";
   string[] readText = File.ReadAllLines(bPath);
   readText = readText.Skip(3).ToArray();

   foreach (var line in readText)
   {
      raw = new decimal[] { Decimal.Parse(line.Substring(9).ToString(), style1) };

      for (int i = 0; i < raw.Length; i++)
      {
         Console.WriteLine("{0} \t {1}", raw[i], i++);
      }

   }

   rawAvgList = raw.Chunk(20).Select(chunk => chunk.Average()).ToArray();
   RawAvg = rawAvgList.Average();
}

So for when I call the array outside of the loop it only grabs the last number in the text file. Am I calling the information wrong? I swear I have tried all the different way to call the numbers from the text file and I just keep running into errors. The error range from it not liking me using skip and substring at the same time or and enumerable error where it returned the error and not the number. Anything to help, Thanks!

1
  • I would recommend trying to avoid SubString if possible, since it will break once the first number grows to large, or if there are the wrong number of white space characters. Prefer string.Split instead, since this is less dependent on any specific alignment. Commented Aug 23, 2022 at 14:47

1 Answer 1

2

You are assigning the variable raw to a new value on each loop iteration, wiping out any value that was stored previously. The end result is that after the loop terminates, it will only contain the value from the last line in the file as you are seeing.

You can declare raw as a List<decimal> instead, then within the loop, you would do

raw.Add(Decimal.Parse(line.Substring(9).ToString(), style1));

This way, once the loop finishes, you'll have all the numbers and not just the last one.

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

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.