tags:

views:

1175

answers:

4

This code works correctely to make a web service call

int numberOfGuests = Convert.ToInt32(search.Guest);

        var list = new List<Guest>();
        Guest adult = new Guest();
        adult.Id = 1;
        adult.Title = "Mr";
        adult.Firstname = "Test";
        adult.Surname = "Test";
        list.Add(adult);
        Guest adult2 = new Guest();
        adult2.Id = 2;
        adult2.Title = "Mr";
        adult2.Firstname = "Test";
        adult2.Surname = "Test";
        list.Add(adult2);

        Guest[] adults = list.ToArray();

How do I build the list dynamically using the numberofguests variable to create the list. The output has to match the output shown exactaly else the web service call fails, so adult.id = 1, adult2.id = 2, adult3.id = 3 etc...

+2  A: 

Do you know about loops?

for (int i = 1; i <= numberofGuests; i++) {
    var adult = new Guest();
    adult.Id = i;
    adult.Title = "Mr";
    adult.Firstname = "Test";
    adult.Surname = "Test";
    list.Add(adult)
}

This runs the code within the loop once from 1 to numberOfGuests, setting the variable i to the current value.

Konrad Rudolph
I think the OP wants to use different data for each loop iteration - for example, Title, FirstName, SurName.
Cerebrus
+2  A: 

You need a for loop. Or, better yet, a decent C# book -- these are really basics of C#.

Anton Gogolev
Basics for most programming languages.
SirDemon
I think the OP wants to use different data for each list member, the fact that the Title etc is the same for each list member is just due to it being a bit of exmaple code.
Ian Ringrose
+1  A: 

The Linq way :-)

    var list = (from i in Enumerable.Range(1, numberOfGuests)
        select new Guest 
        {
          Id = i,
          Title = "Mr.",
          Firstname = "Test",
          Surname = "Test"
        }).ToList();
Miha Markic
A: 

Are you asking how to display a list dynamically? I'm not really sure what the question here is about, as the other answers say if you know the value of numberofGuests then you can just use a loop to go through your list.

I suspect you are wondering how to obtain this information in the first place, am I right? If you want to dynamically add controls to a page (your previous post suggest this was ASP.Net I think?), so that you only display the correct number of controls then take a look at these related questions:

http://stackoverflow.com/questions/128083/dynamically-adding-controls-in-asp-net-repeater

http://stackoverflow.com/questions/733831/asp-net-how-to-dynamically-generate-labels

Steve Haigh