Seb Dammer
Seb Dammer

Reputation: 55

Read specific values out of a text-file and put them in a list

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[...]

Upvotes: 1

Views: 2191

Answers (6)

fubo
fubo

Reputation: 46005

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?

Upvotes: 2

Zein Makki
Zein Makki

Reputation: 30052

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);

Upvotes: 1

DigheadsFerke
DigheadsFerke

Reputation: 307

  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.

Upvotes: 0

Dmitrii Bychenko
Dmitrii Bychenko

Reputation: 186833

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();

Upvotes: 2

Hari Prasad
Hari Prasad

Reputation: 16966

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])
              };
   }

Upvotes: 1

Don Kooker
Don Kooker

Reputation: 1

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

Upvotes: 0

Related Questions