lorenzoid
lorenzoid

Reputation: 1832

C# reading from text file (which has different data types) to get sum of numerical values

So I have a .txt file that reads as the following:

-9
5.23
b
99
Magic
1.333
aa

how would I then loop through it to get the sum of all numerical values, and leave the non-numerical values untouched?

Upvotes: 0

Views: 979

Answers (3)

BLUEPIXY
BLUEPIXY

Reputation: 40145

using System;
using System.IO;
using System.Linq;

class Sample {
    static void Main(){
        string[] data = File.ReadAllLines("data.txt");
        double sum = data.Select( x => {double v ;Double.TryParse(x, out v);return v;}).Sum();
        Console.WriteLine("sum:{0}", sum);
    }
}

Upvotes: 2

KV Prajapati
KV Prajapati

Reputation: 94635

Read text file using System.IO.StreamReader and use Double.TryParse method to parse the numeric data.

Upvotes: 2

Anas Karkoukli
Anas Karkoukli

Reputation: 1342

In your loop you can either:

  • Use int.TryParse

  • Use Regular Expresssion to match only integers.

Upvotes: 0

Related Questions