Search code examples
c#file-read

Effective way of reading text file in c# for line to line operation


I'm having problem in reading text file for line to line addition operation. I have used following syntax

StreamReader reader = new StreamReader("input.txt"); string line; while ((line = reader.ReadLine()) != null) string[] splitted = line.Split('#'); string first = splitted[0].Trim(); string second = splitted[1].Trim();

I have used this syntax to separate the input from text file if file has following values.

12#15

15#7

13#14

23#31

 x= Convert.ToInt32(first);
 y= Convert.ToInt32(second);
 sum = x+y;
 txtBox.text = Convert.ToString(sum);

the problem is it only executes the last line. It only calculate the sum of 23 and 31 and show only but I want to add 12 and 15 first and show it in textbox similarly I want to add others. please help me in forming appropriate syntax.


Solution

  • The question is vague one, however, I suggest using Linq:

      var source = File
        .ReadLines("input.txt")           // read line by line
        .Select(line => line.Split('#'))  // split each line
        //.Where(items => items.Length == 2)  // you may want to filter out the lines
        .Select(items => new {            // convert each line into anonymous class 
           first = items[0].Trim(),
           second = items[1].Trim()
         });
    

    You can add as many Select (line to line opetations) as you want. Then you can proceed the items in a foreach loop:

      foreach (var item in source) { 
        ...
        // Let's read some fields from the anonymous object
        var first = item.first;
        var second = item.second; 
        ...
      }
    

    Edit: according to the edited question you want just to sum up which can be done via Linq as well:

      var result = File
        .ReadLines("input.txt")   
        .Select(line => line.Split('#'))
        //.Where(items => items.Length == 2)  // you may want to filter out the lines
        .Sum(items => int.Parse(items[0]) + int.Parse(items[1]));
    
      txtBox.text = result.ToString();