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...

Johan B
  • 890
  • 3
  • 23
  • 39
steve
  • 25
  • 2
  • 5
  • Isn't this pretty much the same question as this? http://stackoverflow.com/questions/735446/dynamically-build-an-array-for-web-service-c. If not, what new info do you need? – dommer Apr 10 '09 at 10:51

4 Answers4

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.

Konrad Rudolph
  • 530,221
  • 131
  • 937
  • 1,214
  • I think the OP wants to use different data for each loop iteration - for example, Title, FirstName, SurName. – Cerebrus Apr 10 '09 at 10:56
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();
Miha Markic
  • 3,158
  • 22
  • 28
1

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

Anton Gogolev
  • 113,561
  • 39
  • 200
  • 288
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

Community
  • 1
  • 1
Steve
  • 8,469
  • 1
  • 26
  • 37