简体   繁体   中英

C# Sum of values from txt file

How do I take the sum of the values from "Values.txt"? And how do I display it? I am very new to coding, this is for an entry level coding course.

static void Main(string[] args)
{
    StreamReader myReader = new StreamReader("Values.txt");
    string line = "";

    while (line != null)
    {
        line = myReader.ReadLine();
        if (line != null)
            Console.WriteLine(line);
    }
}

Let's assume the text file only contains integers, one per line. I'm not using LINQ for this because you're just starting out and it would be better to get a grounding in normal loops and parsing first. This way is also intolerant of bad data:

//read all the file into an array, one line per array entry
string[] lines = File.ReadAllLines(@"c:\temp\values.txt");

//declare a variable to hold the sum
int sum = 0;

//go through the lines one by one...
foreach(string line in lines)
  //...converting the line to a number and then adding it to the sum
  sum = sum + int.Parse(line);

//print the result
Console.WriteLine("sum is " + sum);

And for compare with how we might write these days with LINQ and other code shortenings:

var lines = File.ReadAllLines(@"c:\temp\values.txt");
var sum = lines.Sum(e => int.TryParse(e, out int x) ? x : 0);
Console.WriteLine($"sum is {sum}");

This latter form uses TryParse to tolerate bad data. Don't hand this code in as your homework- your supervisor will know for sure someone else wrote it; the inline conditional, LINQ, string interpolation, shorthand oarsing output variable and var declarations etc are all things that you wouldn't cover in a programming 101, it's purely for reference and your own curiosity :)

You've got the barebones of reading each line from the file, so what you need to do now is parse the lines as integers. Assuming that each line is solely a number, you can do the following:

What you would do is declare a variable, an integer (you can change this) that stores the sum, starting from 0. Then, inside the null check if block, you can put the following:

// Check whether the line is an integer.
if (Int32.TryParse(line, out int parseValue) {
    // Add the value to the sum.
    sum += parseValue;
}

This is my attempt on a single line of code.

ReadAllLines will read all the lines into an Array of strings. You can use the built in method .Sum() on an array to add up all the numbers, but since the array is made up of strings, we can convert the string to integer by using int.Parse().

Definition of ReadAllLines
Definition of Array.Sum()

Now since we know how to read up all the lines from a file and convert them to numbers, we can use the statement Sum(x => int.Parse(x)) .. which means, parse the string to number and sum them all up.

int sum = File.ReadAllLines(@"C:\temp\numbers.txt").Sum(x => int.Parse(x));
Console.WriteLine(sum);
// sum = 29

the numbers.txt file has content:

10
10
2
2
2
3

Process in Detail:

  • File.ReadAllLines(FilePath) generates Array of strings. We can run various processes on the array, like Sum, Count, Average, etc.
  • (x => int.Parse(x)) itself generates an array of numbers based on each line (represented by x) in the string array. If we can get the number array, we can use the method of Sum(arrayOfNumbers)
  • Array.Sum(x => int.Parse(x)) generates single number which is a sum of all numbers of Array.

First you need to read file and get all lines. Then loop each line and check whether it is number or not and then add.

 string[] strNumbers = System.IO.File.ReadAllLines(@"C:\MyFolder\Values.txt");
 int count = 0;
 foreach (string strNumber in strNumbers)
 {
   if (Int32.TryParse(strNumber, out int number)) 
   {
      count = count + number;
   }
}

Console.WriteLine("Total : " +count);
var sum = File.ReadLines("Values.txt")
    .Select(line => Convert.ToInt32(line))
    .Sum();
Console.WriteLine(sum);

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