2017-02-28 6 views
0

私は次のコードがありますが、私はコードが行の非整数値を無視するように助けが必要です。現在、各行ごとの合計を計算しますが、非整数値を満たした時点で停止します。また、どのように私はすべての行の総計を得ることができますか?コードを読み取る1行あたりの合計の合計は機能しますが、整数以外の値を無視する必要があります。私はまた総計を見つける必要があります

私の入力ファイルは、この

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 Check Now –

答えて

0

は、あなたのタスクは、LINQのは、のために設計されたものである、LINQのを使用してみてください:あなたはParseの代わりにTryParseを使用することができます

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

。文句を言わない例外を取得し、ループが停止し、あなたを確保するための

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:

をあなたはこれに... ...

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

をこの部分を変更することができます

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

私の標準的なライブラリメソッドの1つを最大限に活用するので、この問題は本当に好きです。

文字列が有効な番号でない場合には、例外を防止して最初に開始することができます。

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 
関連する問題