Dynamically build an array for web service

后端 未结 5 954
既然无缘
既然无缘 2021-01-27 01:55

I\'m using C# and asp.net to query a web service.

The user will enter the number of guests and then I need to add that number of guests to the web service call. Creati

相关标签:
5条回答
  • 2021-01-27 02:17

    All the other answers have suggested using List<Guest> and normally I'd agree - but in this case there's really no need as it seems you know the size beforehand:

    Guest[] guests = new Guest[numberOfGuests];
    for (int i=0; i < numberOfGuests; i++)
    {
        Guest guest = new Guest();
        // Fill in information about the guest here
        // based on the web form
        guests[i] = guest;
    }
    

    That's not to say you shouldn't use a List<Guest> if that's more convenient in any way - it's just that the (probably) biggest benefit of using a List<T> is that you don't need to know the size in advance. As that's not relevant here (unless I'm missing something) there's not as much reason to use a list.

    0 讨论(0)
  • 2021-01-27 02:17

    I suggest you use a List<Guest>. You can initialize the size with the number of guests when you create it, but that is really just an optimization. If you want to add more guests later, you can do that and the List will resize as necessary.

    List has a ToArray() method if you want to turn the list into an array for some reason.

    0 讨论(0)
  • 2021-01-27 02:20

    Instead of using a raw array why not use ArrayList or List<Object>?

    var list = new List<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();
    
    0 讨论(0)
  • 2021-01-27 02:26

    I'd suggest using a List rather than an array in this case. You can convert it to an array once it is populated if you still need it as an array.

    0 讨论(0)
  • 2021-01-27 02:39
    List<Guest> guests = new List<Guest>();
    for(int i=0; i<numberOfGuests; i++)
    {
      guests.Add(new Guest()
      {
        Title = "Mr",
        Firstname = "Test",
      });
    }
    return guests.ToArray();
    
    0 讨论(0)
提交回复
热议问题