简体   繁体   中英

c# list<t>; how to add objects like a foreach loop but without foreach?

I'm new to c# and need help with lists and objects.

Severe edit as suggested..

what I really want to do is

List<Item> MyList = new List<Item>();

Item MyItem = new Item();

MyItem.Colour = "red";
MyList.Add(MyItem);
MyItem.Colour = "blue";
MyList.Add(MyItem);
MyItem.Colour = "white";
MyList.Add(MyItem);

And my list will now contain 3 elements - red, blue, white.

I think I can do this by:

Item MyItem = new Item();

MyItem.Colour = "red";
MyList.Add(MyItem);

MyIten = new Item();
MyItem.Colour = "blue";

MyItem = new Item();
MyList.Add(MyItem);

MyItem = new Item();
MyItem.Colour = "white";
MyList.Add(MyItem);

Again, this is simplified. With my real data there are a lot more elements.

I'll try that out;

TIA - Andrew

A better way to read a file in the case will be to use a StreamReader that wraps the FileStream you read from. The StreamReader allows you to iterate through the file line per line without reading in the entire file beforehand.

So you can do something like this:

while((var line = streamReader.ReadLine()) != null) { // Iterate through the file here }

Inside the while loop you can devise a simple state machine that either reads a header, a Job or the jobs Details depending on where you are in the file.

Based on your description, I'm guessing you have a scoping problem. Your code should look something like this... pay particular attention to where each variable is set. Also, with these types of scenarios it is often helpful to create a static factory method called Parse that constructs the object from a string.

string line;
System.IO.StreamReader file = new System.IO.StreamReader(filename);

Job myJob = null;
Detail myDetail = null;
while((line = file.ReadLine()) != null)
{
    var lineType = getLineType(line);
    switch(lineType){
        case Job:
           myJob = new Job();
           break;
        case newDetail:
           if(myDetail != null)
           {
               myJob.Details.Add(myDetail); 
           }
           Detail myDetail = new Detail();
           break;
        case continueDetail:
           //set some detail properties
           break;
   }

}

One more time

List<Item> MyList = new List<Item>();
Item MyItem = new Item();
MyItem.Colour = "red";
MyList.Add(MyItem);
MyItem = new Item(); //<-- this is what you are missing
MyItem.Colour = "blue";
MyList.Add(MyItem);

HTH, but your question is a bit unclear.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM