method to add an object to a list from a stream

  • Thread starter Thread starter dawn
  • Start date Start date
D

dawn

SO I am having issues with adding items to a list....I have created a
file StreamReader which reads values from a file I have connected
through streams. WHat I am trying to do, is depending on whether the
row has 4 values, or 5values instantiate an object(of previous classes
I have created) and store those objects in a list. SO the method needs
to read the entire document, and when a row has four items, instantiate
object A, five items instantiate object B, and store these items in a
list. I know that I probably messed up terms, but hopefully someone
can help me!!
 
Can you clarify things: when you say "whether the row has 4 values, or
5values", do you mean that you are essentially parsing a format (e.g.
csv, tsv etc)? In which case, something like the following might work.
Note I haven't handled any nuances (quotes etc) from csv/tsv - better
readers may be available ;-p
I have used ArrayList to a: support 1.1, and b: because you didn't
indicate that the two types shared any base/interface. Likewise the
default ctor etc. You could use a typed List<T> also.

using (StreamReader sr = new StreamReader(path))
{
string line;
while ((line = sr.ReadLine()) != null)
{
object item;
string[] cells = line.Split('\t');
switch (cells.Length)
{
case 4:
item = new SomeTypeA();
// init
break;
case 5:
item = new SomeTypeB();
// init
break;
default:
throw new NotSupportedException();
// or continue; to ignore the row
}
list.Add(item);
}
}
Marc
 
Sorry, I am new at this....Yes I am parsing a format(csv) and the two
types that I am instantiating both inherit from base Class C. Sorry,
hopefully that helps clear things up..THanks for the help though!
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Back
Top