2

I want to increase my basePremium(=200) by a certain percentage, the percentages are stored in rows of the second column in my csv file. the percentage will be determined by the selection the user makes from a drop-down list that has the values from the first column stored in it.

I want to store this calculation in a method in a class that I can use in different forms.

  public void premiumCalc()
    {

        StreamReader reader = File.OpenText("JobList.csv");

        while (!reader.EndOfStream)
        {
            String line = reader.ReadLine();
            String[] values = line.Split(',');
        }
        reader.Close(); //close the csv file
    }
    double basePremium = 200.00;



    }
}
kitty
  • 21
  • 1
  • 5
  • 2
    Have you tried `values[1]` ? Also, I would suggest you use an actual csv reader library – OneCricketeer Dec 28 '19 at 21:24
  • @cricket_007 where would I add 'values[1]' and what do you mean an actual csv reader library? – kitty Dec 28 '19 at 21:31
  • In the loop? After you actually get the array? And I mean something other than a StreamReader. Many lists of ways here https://stackoverflow.com/questions/3507498/reading-csv-files-using-c-sharp – OneCricketeer Dec 28 '19 at 21:37

2 Answers2

0

In somewhat object-oriented approach, you may solve it this way:

  1. Create a class containing three properties PropertyColumn1,PropertyColumn2,BasePremium, and CalculatedPremium
  2. Populate the list with each row from CSV file
  3. Loop thru each item and assign the value to CalculatedPremium property

HTH

rdagumampan
  • 459
  • 4
  • 16
0

You can try ExcelDataReader library to read your CSV file.
And here is example of method that will return percentage based on user selection:

public double GetPercentage(string key)
{
    using (var stream = new FileStream("JobList.csv", FileMode.Open))
    {
        using (var reader = ExcelReaderFactory.CreateCsvReader(stream))
        {
            while (reader.Read()) 
            {
                var valueColumn1 = reader.GetValue(0)?.ToString();
                if (key == valueColumn1)
                {
                    return double.TryParse(reader.GetValue(1)?.ToString(), out var percentage)
                        ? percentage
                        : 0;
                }
            }
        }
    }

    return 0;
}
Roman.Pavelko
  • 1,555
  • 2
  • 15
  • 18