开发者

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

开发者 https://www.devze.com 2023-03-07 13:09 出处:网络
I\'m new to c# and need help with lists and objects. Severe edit as suggested.. what I r开发者_如何学编程eally want to do is

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

Severe edit as suggested..

what I r开发者_如何学编程eally 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.

0

精彩评论

暂无评论...
验证码 换一张
取 消