1

The program is meant to read in information from a .csv file; then with the data from this file the Product objects are to be created and then stored in a list.

My problem is that I have no idea how to transfer the data from the .csv file that will be split up by ',' and stored in an array to the constructor objects. Any help would be greatly appreciated.

The .csv looks like this:

What the .csv Looks Like

Here is my code thus far:

class Product
{
    public string ID { get; set; }
    public string Name { get; set; }
    public string Description { get; set; }
    public string Price { get; set; }
    public string StockAvailable { get; set; }
    public string WeeklySales { get; set; }

    // Constructor 
    public Product(string iD, string name, string Desc, string price, string StockAva, string weeklysales)
    {
        ID = iD;
        Name = name;
        Description = Desc;
        Price = price;
        StockAvailable = StockAva;
        WeeklySales = weeklysales;
    }
}

private static void ReadProductFile()
{
    string productPath = GetDataDirectory("prod");

    string[] fileData = File.ReadAllLines(productPath);

    string[] productDetails = new string[20];

    for (int i = 0; i < fileData.Length; i++)
    {
        productDetails = fileData[i].Split(',');

        // I have no idea what do do next!
    }
}
J0e3gan
  • 8,740
  • 10
  • 53
  • 80
Razis
  • 13
  • 2

2 Answers2

1
List<Product> myProducts = new List<Product>();

...

for (int i = 0; i < fileData.Length; i++)
{
    productDetails = fileData[i].Split(',');

    var p = new Product(productDetails[0],
                        productDetails[1],
                        ...
                        productDetails[5]));
    myProducts.Add(p);
}

As others have mentioned, Split(',') is not the most reliable way to parse a CSV file -- what if the product description contains a ,? Using a proper C# CSV parser will fix these issues for you.

Community
  • 1
  • 1
Heinzi
  • 167,459
  • 57
  • 363
  • 519
  • Indeed. I don't think it's a secondary issue, btw... it's actually the OP's main question: *"My problem is that I have no idea how to transfer the data [...] stored in an array to the constructor objects."* – Heinzi Dec 21 '14 at 17:20
  • I think Heinzi's answer is pretty much what I'm looking far. My knowledge is pretty basic at the moment. The information I gave is part of a question given to us to complete. Parsing the CSV file using Split(',') is as advanced as we have gone at the moment. We never covered Lists, but the lecturer threw them in to make us think a little more I guess... not that they seem to be that different from arays, etc. – Razis Dec 21 '14 at 17:59
  • The program will use a Product class with the following properties ID, Name, Description, Price, StockAvailable, WeeklySales The program will function by first reading the product information. The program will then create a number of Product objects based on this file and store these Products in a List of Products. The program will then read in Sales information from the sales file and update the product list with the weekly sales figure. Finally the program will write updated information to an updated product details file ensuring the stock value is changed to reflect the sales. – Razis Dec 21 '14 at 18:01
  • As you can probably see we are at a fairly basic level at the moment! Thanks for all the help by the way :) – Razis Dec 21 '14 at 18:02
  • @user4382995: You're welcome! About arrays vs lists: The advantage of lists is that they have *variable size*: You can easily add and remove elements from them -- that's not so easy with arrays, which are fixed-sized. – Heinzi Dec 21 '14 at 18:04
0

This is simple, but requires you to know beforehand the order of fields in your csv file. Once you know that, it is simply a matter of reading all specific fields and send them to the constructor of the Product class (which fortunately already accepts the field values).

You should probably use a CSV reader for this task. That will make parsing and reading individual field values much easier. There is a built-in CSV parser within .NET class library. See this SO post for details and usage.

Your function would look something like below if you use CSV parser:

private static List<Product> ReadProductFile()
{
    string productPath = GetDataDirectory("prod");

    if(!System.IO.File.Exists(productPath)) return null;

    var lst = new List<Product>();

    TextFieldParser parser = new TextFieldParser(productPath);
    parser.TextFieldType = FieldType.Delimited;
    parser.SetDelimiters(",");

    while (!parser.EndOfData) 
    {
        string[] fields = parser.ReadFields();
        foreach (string field in fields) 
        {
            try
            {
                //assuming that the order of fields in the CSV file is the same as the 
                //order of arguments of Product's constructor.
                Product p = new Product(field[0], field[1], ...);
                lst.Add(p);
            }
            catch(Exception ee)
            {
                //Log error somewhere and continue with the rest of the CSV
            }
        }
    }

    parser.Close();

    return lst;
}
Community
  • 1
  • 1
dotNET
  • 33,414
  • 24
  • 162
  • 251