0

Beginner programmer here so please keep (explanation of) answers as simple as possible. For an assignment we got a text file that contains a large amount of lines. Each line is a different 'Order' with an ordernumber, location, frequency (amount of times per week), and a few other arguments. Example:

18; New York; 3PWK; ***; ***; etc

I've made it so that each line is read and stored in a string with

string[] orders = System.IO.File.ReadAllLines(@<filepath here>);

And I've made a separate class called "Order" which has a get+set for all the properties like ordernumber, etc.

Now I'm stuck on how to actually get the values in there. I know how string splitting works but not how I can make unique objects in a loop. I'd need something that created a new Order for every line and then assign Order.ordernumber, Order.location etc.

Any help would be MUCH appreciated!

Soner Gönül
  • 97,193
  • 102
  • 206
  • 364
  • Do some reading first, there are loads of resources on this kind of thing. First google result: http://stackoverflow.com/questions/7702573/importing-csv-data-into-c-sharp-classes - Being a beginner is one thing, not being resourceful enough prior to asking for help is another. –  Dec 10 '13 at 12:29

3 Answers3

2

An easy approach will be to make a class to define the orders like this:

public class Order{
  public string OrderNumber{get;set;}
  public string OrderId{get;set;}
  public string OrderSomeThingElse{get;set;}
}

Then initialize a List:

var orderList = new List<Order>();

Then loop through and populate it:

foreach( var order in orders ){
  var splitString = order.Split(';');
  orderList.Add( new Order{
    OrderNumber = splitString[0],
    OrderId = splitString[1],
    OrderSomeThingElse = splitString[2]
  });
}

If you want an easy, but not that elegant approach, this is it.

Øyvind Bråthen
  • 59,338
  • 27
  • 124
  • 151
1

In addition to all the good answers you've already received. I recommend you to use File.ReadLines() instead File.ReadAllLines() Because you are reading large file.

The ReadLines and ReadAllLines methods differ as follows: When you use ReadLines, you can start enumerating the collection of strings before the whole collection is returned; when you use ReadAllLines, you must wait for the whole array of strings be returned before you can access the array. Therefore, when you are working with very large files, ReadLines can be more efficient. MSDN

Jacob
  • 751
  • 1
  • 6
  • 18
0

Unless I misunderstand... do you mean something like this?

var ordersCollection = new List<Order>();

foreach (var order in orders)
{
    var o = new Order();
    o.PropertyName = ""; // Assign your property values like this

    ordersCollection.Add(o);
}

// ordersCollection is now full of your orders.
BenjaminPaul
  • 2,931
  • 19
  • 18