1

This code works correctly 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 exactly else the web service call fails, so adult.id = 1, adult2.id = 2, adult3.id = 3, etc...

1

4 Answers 4

4

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.

Sign up to request clarification or add additional context in comments.

1 Comment

I think the OP wants to use different data for each loop iteration - for example, Title, FirstName, SurName.
2

The Linq way :-)

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

Comments

1

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

2 Comments

Basics for most programming languages.
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.
0

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:

Dynamically adding controls in ASP.NET Repeater

ASP.NET - How to dynamically generate Labels

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.