簡體   English   中英

C#來自txt文件的值的總和

[英]C# Sum of values from txt file

如何從“Values.txt”中獲取值的總和? 以及如何顯示它? 我對編碼很陌生,這是一個入門級的編碼課程。

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

假設文本文件只包含整數,每行一個。 我沒有為此使用 LINQ,因為您才剛剛開始,最好先了解正常循環並先進行解析。 這種方式也不能容忍壞數據:

//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);

並與我們現在使用 LINQ 和其他代碼縮短編寫的方式進行比較:

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

后一種形式使用 TryParse 來容忍壞數據。 不要把這段代碼當作你的作業——你的主管肯定知道是其他人寫的; 內聯條件、LINQ、字符串插值、速記輸出變量和 var 聲明等都是您不會在編程 101 中涵蓋的內容,僅供參考和您自己的好奇心:)

您已經獲得了從文件中讀取每一行的准系統,因此您現在需要做的是將這些行解析為整數。 假設每一行只是一個數字,您可以執行以下操作:

您要做的是聲明一個變量,一個存儲總和的整數(您可以更改它),從 0 開始。然后,在 null check if 塊中,您可以輸入以下內容:

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

這是我對單行代碼的嘗試。

ReadAllLines 將所有行讀入一個字符串數組。 您可以在數組上使用內置方法 .Sum() 將所有數字相加,但由於數組由字符串組成,我們可以使用 int.Parse() 將字符串轉換為整數。

ReadAllLines 的定義
Array.Sum() 的定義

現在既然我們知道如何從文件中讀取所有行並將它們轉換為數字,我們可以使用語句Sum(x => int.Parse(x)) .. 這意味着,將字符串解析為數字並將它們相加都起來。

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

numbers.txt 文件有內容:

10
10
2
2
2
3

詳細流程:

  • File.ReadAllLines(FilePath)生成字符串數組。 我們可以在數組上運行各種進程,如 Sum、Count、Average 等。
  • (x => int.Parse(x))本身根據字符串數組中的each line (由 x 表示(x => int.Parse(x))生成一個數字數組。 如果我們能得到數字數組,我們可以使用 Sum(arrayOfNumbers) 的方法
  • Array.Sum(x => int.Parse(x))生成單個數字,它是 Array 的所有數字的總和。

首先,您需要讀取文件並獲取所有行。 然后循環每一行並檢查它是否為數字,然后添加。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM