views:

36

answers:

1

I am trying to set XElements with an ArrayList and having a bit of trouble. I basically want to be able to do a foreach loop, but not sure where I need to insert it.

ArrayList cities = new ArrayList();
foreach (ListItem item in lstCities.Items)
{
    cities.Add(item.Text);
}

new XElement("Cities", cities //not sure what to do here
                            .Select(x=>new XElement("City",x)))  

This does not work, though it worked okay with this, but I want the city names, not array number

new XElement("Countries", lstCountry.GetSelectedIndices()
                              .Select(x => new XElement("Country", x))
+1  A: 

Any reason why you're using an ArrayList instead of a List<string> to start with?

If you're forced to use ArrayList then you could do:

cities.Cast<string>()
      .Select(x => new XElement("City", x)

... but you'd be better off using List<string> if possible.

Alternatively:

new XElement("Cities", lstCities.Items
                                .Cast<ListItem>()
                                .Select(x => new XElement("City", x.Text)))
Jon Skeet
@Jon: I missed your rolling over 200K (which appears to have been a couple hours ago). Was there a party?
James Curran
@Jon: List<string> doesn't seem to have a Items definition... unless I am missing something
Spooks
nevermind, when creating a List<string> (List<string> cities = new List<string>();) I can't pull any items, but I just used my listBox and that worked fine, thanks!
Spooks
@Spooks: You would add to the `List<string>` in exactly the same way you were adding to the `ArrayList`. I *strongly* recommend that you learn more about the core collection classes in .NET before going too much further with databases, XML etc.
Jon Skeet
@Jon I know how to add to a List. foreach (ListItem item in lstCities.Items) { cities.Add(item.Text); }I am just saying cities.Items does not work, there is no definition for Items.
Spooks
@Spooks: But where did anyone suggest using `cities.Items`?
Jon Skeet
@Jon Oh! Just read through my code, you were using it off my lstCities, I had forgotten I had added that, and thought you were that was your name for your new List<string> my bad.
Spooks