1

I have a text-file with many lines, each line looks like this: "string string double double" between each value is a space. I'd like to read out the first string and last double of every line and put these two values in a existing list. That is my code so far, but it doesnt really work.

    private void bOpen_Click(object sender, RoutedEventArgs e)
    {
        bool exists = File.Exists(@"C:\Users\p2\Desktop\Liste.txt");

        if (exists == true)
        {
            StringBuilder sb = new StringBuilder();

            using (StreamReader sr = new StreamReader(@"C:\Users\p2\Desktop\Liste.txt"))
            {
                Vgl comp = new Vgl();
                comp.name = Abzahlungsdarlehenrechner.zgName;
                comp.gErg = Abzahlungsdarlehenrechner.zgErg;

                GlobaleDaten.VglDaten.Add(comp);


                int i = 0;
                string line = File.ReadLines(@"Liste.txt").Skip(0).Take(1).First();
                while ((line = sr.ReadLine()) != null)
                {
                    sb.Append((line));
                    listBox.Items.Add(line);
                    GlobaleDaten.VglDaten.Add(comp);

                    i++;
                }
            }
        }

I have already read this, but it didnt help How do I read specific value[...]

Community
  • 1
  • 1
Seb Dammer
  • 55
  • 8

6 Answers6

2

how about

List<Vgl> Result = File.ReadLines(@"C:\Users\p2\Desktop\Liste.txt")
            .Select(x => new Vgl()
            {
                name = x.Split(' ').First(),
                gErg = decimal.Parse(x.Split(' ').Last(), NumberStyles.AllowCurrencySymbol)
            }) 
            .ToList();

I would avoid storing money within doulbe values because this could lead to rounding issues. Use decimal instead. Examples here: Is a double really unsuitable for money?

Community
  • 1
  • 1
fubo
  • 44,811
  • 17
  • 103
  • 137
  • @SebDammer you can use `NumberStyles.AllowCurrencySymbol` to avoid exceptions with currency symbols like € - updated my answer – fubo Jul 07 '16 at 11:48
  • Didnt know that, thanks for the hint :) But suddenly it shows an error all the time, no matter which code I use. Dmitry Bychenkos code for example worked fluently. "System.FormatException" again... – Seb Dammer Jul 07 '16 at 12:07
  • ok that's difficult to say without knowing the file. A space within the string or a `,` instead of a `.` as seperator could be the reason. – fubo Jul 07 '16 at 12:12
  • Seems the NumberStyles.CurrencySymbol is the reason. Do you know why it doesnt work? The code for my list entrys is: listBox.Items.Add(Ab.zgName + " " + "[Ab]" + " " +Ab.zmErg.ToString("0.00") + "€" + " " + Ab.zgErg.ToString("0.00") + "€"); – Seb Dammer Jul 07 '16 at 12:19
  • `Ab.zgName` could contain spaces? that could be one reason – fubo Jul 07 '16 at 12:41
2

You can try Linq:

var source = File
  .ReadLines(@"C:\Users\p2\Desktop\Liste.txt")
  .Select(line => line.Split(' '))
  .Select(items => new Vgl() {
       name = items[0], 
       gErg = double.Parse(items[3])
     });

// If you want to add into existing list
GlobaleDaten.VglDaten.AddRange(source);

// If you want to create a new list
//List<Vgl> list = source.ToList();
Dmitry Bychenko
  • 180,369
  • 20
  • 160
  • 215
1

You can use:

string[] splitBySpace = line.Split(' ');

string first = splitBySpace.ElementAt(0);
decimal last = Convert.ToDecimal(splitBySpace.ElementAt(splitBySpace.Length - 1));

Edit : To Handle Currency symbol:

string[] splitBySpace = line.Split(' ');
string pattern = @"[^0-9\.\,]+";

string first = splitBySpace.ElementAt(0);
string last = (new Regex(pattern)).Split(splitBySpace.ElementAt(splitBySpace.Length - 1))
                                    .FirstOrDefault();

decimal lastDecimal;
bool success = decimal.TryParse(last, out lastDecimal);
Zein Makki
  • 29,485
  • 6
  • 52
  • 63
  • should have had put it inside the while-loop of my code? cause if I dont it shows some errors – Seb Dammer Jul 07 '16 at 07:40
  • @SebDammer It should be inside the while `((line = sr.ReadLine()) != null) { }` in your code. – Zein Makki Jul 07 '16 at 07:42
  • It seems to work. But I'm going to have to rewrite some of my code a bit. I need to put the values in a list for a comparing method in another class. Your method seems to have some problems with the €-Signs, just like fubo's method. – Seb Dammer Jul 07 '16 at 07:53
  • 1
    @SebDammer check the edit to handle Currency symbols. – Zein Makki Jul 07 '16 at 08:14
1

I agree with @Dmitry and fubo, if you are looking for alternatives, you could try this.

var source = File
  .ReadLines(@"C:\Users\p2\Desktop\Liste.txt")
  .Select(line =>
   {
        var splits = line.Split(' '));
        return new Vgl() 
              {
                  name = splits[0], 
                 gErg = double.Parse(splits[3])
              };
   }
Hari Prasad
  • 16,716
  • 4
  • 21
  • 35
0

use string.split using space as the delimiter on line to the string into an array with each value. Then just access the first and last array element. Of course, if you aren't absolutely certain that each line contains exactly 4 values, you may want to inspect the length of the array to ensure there are at least 4 values.

reference on using split: https://msdn.microsoft.com/en-us/library/ms228388.aspx

0
  1. Read the whole file as a string.
  2. Split the string in a foreach loop using \r\n as a row separator. Add each row to a list of strings.
  3. Iterate through that list and split again each record in another loop using space as field separator and put them into another list of strings.
  4. Now you have all the four fields containig one row. Now just use First and Last methods to get the first word and the last number.
DigheadsFerke
  • 307
  • 1
  • 8