2017-02-28 30 views
0

我有下面的代碼,但我需要幫助,使代碼忽略連續的非整數值。目前它計算每行的總和,但是如果它滿足非整數值時停止。我怎麼能得到所有行的總計?要讀取的代碼總計每行的總和,但需要忽略非整數值,仍然有一些總數。我也需要找到總計

我輸入的文件看起來像這樣

50,22,30,10,50,5,40

25,10,10,46,16,17,90

15, c80x,2

X,2,3,

公共類節目 {

static string currentLine; //variable for holding the current line that has been read from the file 
    static int[] theList; // array to hold integer values read from the theLine 
    static int LineNumber = 1; //A count keeping the current line's number 
    static int theSum; //Variable to hold the sum of the numbers successfully ready from the file 

    static int total; 
    public static void Main(string[] args) 
    { 
     var fileStream = new FileStream(@"InputData.txt", FileMode.Open, FileAccess.Read); 
     using (var streamReader = new StreamReader(fileStream, Encoding.UTF8)) 
     { 
      //string line; 



      while ((currentLine = streamReader.ReadLine()) != null) 
      { 

       Add(currentLine); // process the line 
      } 


     } 
     Console.ReadLine(); 

     fileStream.Dispose();//Release the file 
    } 




    public static void Add(string numbers) 
    { 

     if (numbers.Contains(";")) //Check if line contains semi-colon as the delimiter 
     { 
      theList = numbers.Trim().Split(',').Select(int.Parse).ToArray(); 


      //add input elements to array excluding the ; character 
     } 
     else if (numbers.Contains(",")) //Check if the line contains comma as the delimiter 
     { 
      theList = numbers.Trim().Split(',').Select(int.Parse).ToArray(); 
      // add input elements to array excluding the , character 
     } 
     else 
     { 
      throw new ArgumentException(); 
     } 
     theSum = theList.Sum(); 



     Console.WriteLine("The sum of the numbers entered at line : " + 
      LineNumber.ToString() + " is : " + theSum); 
     LineNumber++; 



    } 
+0

你的輸入文件是什麼樣的? – px06

+0

@ px06立即檢查 –

回答

0

嘗試使用的LINQ,你的任務就是一個LINQ的已被設計爲:

using System.Linq; 

    ... 

    public static void Main(string[] args) { 
    var result = File 
     .ReadLines(@"InputData.txt") 
     .Select(line => line 
      .Split(new char[] { ',', ';'}, StringSplitOptions.RemoveEmptyEntries) 
      .Select(item => { 
      int v; 
      bool parsed = int.TryParse(item, out v); 

      return new { 
       value = v, 
       isParsed = parsed, 
      }; 
      }) 
      .Where(item => item.isParsed) 
      .Sum(item => item.value)); 

    int lineIndex = 0; 
    long grandTotal = 0; 

    foreach (var sum in result) { 
     Console.WriteLine( 
     $"The sum of the numbers entered at line {lineIndex + 1} is: {sum}"); 

     lineIndex += 1; 
     grandTotal += sum; 
    } 

    Console.Write($"Grand total is {grandTotal}"); 
    } 
+0

'Select(item => int.Parse(item))與OP的Select(int.Parse)'在語義上是相同的,並且由於'StringSplitOptions.RemoveEmptyEntries'只刪除空條目,整數條目,問題仍未解決。 – Sefe

+0

@ Sefe:我明白了,謝謝!沒有注意到問題編輯。 –

0

可以使用TryParse而不是Parse。你可以改變這部分...

numbers.Trim().Split(',').Select(int.Parse).ToArray() 

...這樣的:

numbers.Trim().Split(',') 
    .Select(text => { 
     int result; 
     bool isNumeric = Int32.TryParse(text, out result); 
     return new { result, isNumeric }; 
    }) 
    .Where(entry => entry.isNumeric) 
    .Select(entry => entry.result) 
    .ToArray() 
0

更好地利用int.TryParse()確保你不會得到一個異常,循環停止: Insetad的:

theList = numbers.Trim().Split(',').Select(int.Parse).ToArray(); 

用途:

string[] list=numbers.Trim().Split(','); 
List<int> theList=new List<int>(); 
foreach (string item in list) 
{ 
    int result; 
    if (int.TryParse(out result) 
    { 
     theList.Add(result); 
    } 
} 

也不要拋出任何異常(留下其他空白),因爲如果它再次進入,否則它會停止循環。

0

我真的很喜歡這個問題,因爲它充分利用了我的一個標準庫方法。

因此,讓我們首先通過防止異常,當一個字符串不是一個有效的數字。

public static class IntExt 
{ 
    public static int? ParseNullable(string text) 
    { 
     int result; 
     return int.TryParse(text, out result) ? result : (int?)null; 
    } 
} 

當字符串不是數字時,此方法返回null。這是非常容易查詢。所以我們只需運行一個簡單的LINQ查詢來獲得我們的答案。

var result = numbers.Trim().Split(',').Sum(x => IntExt.ParseNullable(x) ?? 0); 

在上面的代碼段我只想指出,?? 0手段「或者如果返回null 0」。它是C#6中的一個新操作符。

最後,我們只需要計算行數。

int total; 
using (var streamReader = new StreamReader(fileStream, Encoding.UTF8)) 
    while ((currentLine = streamReader.ReadLine()) != null) 
     total += currentLine.Trim().Split(',').Sum(x => IntExt.ParseNullable(x) ?? 0); 
//total now contains the grand total