Input: All the sales data for any given day, extracted from a string by the following code:
class Program
{
static void Main(string[] args)
{
List<Sale> Sales = new List<Sale>();
// int l = 1;
using (StreamReader reader = new StreamReader("file.dat"))
{
string line;
var locations = new Dictionary<string, int[]>() {
{"210", new [] {405, 4, 128, 12, 141, 12, 247, 15, 121, 3}},
{"310", new [] {321, 4, 112, 12, 125, 12, 230, 15, 105, 3}},
{"410", new [] {477, 4, 112, 12, 125, 12, 360, 15, 105, 3}}
};
while ((line = reader.ReadLine()) != null)
{
var lineStart = line.Substring(0, 3);
if (lineStart == "210" || lineStart == "310" || lineStart == "410")
{
var currentLocations = locations[lineStart];
var letters = line.Substring(currentLocations[0], currentLocations[1]);
var volume =
int.Parse(line.Substring(currentLocations[2], currentLocations[3])) +
int.Parse(line.Substring(currentLocations[4], currentLocations[5]));
var price = long.Parse(line.Substring(currentLocations[6], currentLocations[7]));
var mvolume = price * volume;
var currency = line.Substring(currentLocations[8], currentLocations[9]);
This takes the required information I want from the string.
I have a separate class with the same fields as those variables, (but with slightly different names).
public class Sale
{
private int CashTotal;
private string codeletters;
private string Crncy;
}
further down in my main code I have:
Sale s = new Sale();
Sales.Add(s);
(this is my full code so far, just broken into parts, it reads from top to bottom as it is in the program – apart from the new class).
What I’m struggling to do at this point is to load the values in each of the var’s into the fields in the class (store Currency as Crncy, mvolume as totalcash, and letters as codeletters), store that object (Sale) into the list (Sales), and then repeat it again. I’m pretty sure there’s a really basic solution for this but I’m stuffed if I can think of it.
edit: Sorry about that, resolved that one and edited the code, accordingly, I’ll show you what I tried which didn’t work but should convey the logic of what I’m trying to do:
Sale.CashTotal = mvolume;
Sale.Crncy = currency;
Sale.codeletters = letters;
I’ve broken down the string into its component parts, but I can only store one object in a list, so i need to recombine them together as a Sale, and store that in the list instead, but getting those values into the Sale is proving to be problematic.
You’ve declared your fields as
private, so they are not accessible out of the class. You can either declare a public constructor and pass the values there. Also you could add publiv properties with onlygetaccessors:This would then be used:
Or you could make them
public:However public fields are definetely bad design, so you’d better make them auto properties:
Please, read MSDN for more info: Access Modifiers