Reputation: 25
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...
Upvotes: 1
Views: 9110
Reputation: 8511
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
Upvotes: 0
Reputation: 3240
The Linq way :-)
var list = (from i in Enumerable.Range(1, numberOfGuests)
select new Guest
{
Id = i,
Title = "Mr.",
Firstname = "Test",
Surname = "Test"
}).ToList();
Upvotes: 2
Reputation: 115691
You need a for loop. Or, better yet, a decent C# book -- these are really basics of C#.
Upvotes: 1
Reputation: 545508
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.
Upvotes: 4