tags:

views:

33

answers:

1

Hi, I have an ASP.NET webform that has a listbox (lbxRegions) with multi-select option enabled. In my db, I have a table with an xml field that holds a list of regions. I need to populate the listbox with all available regions and then "check off" the list items that match the regions in the db table. The list options also need to be ordered by region name. So, I wrote the following code that works just fine -- no problems. But I was wondering if anyone can think of a better (more succinct, more efficient) way to have done the same thing. Thanks in advance.

        Dim allRegions = XElement.Load(Server.MapPath(Request.ApplicationPath) & "\Regions.xml").<country>.<regions>.<region>
        Dim selectedRegions = (From ev In dc.Events Where ev.EventId = 2951).Single.CEURegions.<country>.<regions>.<region>
        Dim unselectedRegions = allRegions.Except(selectedRegions)

        Dim selectedItems = From x In selectedRegions Select New ListItem() _
                                With {.Value = x.@code, .Text = x.Value, .Selected = True}

        Dim unselectedItems = From x In unselectedRegions Select New ListItem() _
                                With {.Value = x.@code, .Text = x.Value}

        Dim allItems = selectedItems.Union(unselectedItems).OrderBy(Function(x) x.Text)

        lbxRegions.Items.AddRange(allItems.ToArray())

P.S. You can post code in C# if you like.

+1  A: 
allRegions = GetAllRegions();
selectedRegions = GetSelectedRegions();

allItems = from r in allRegions
  select new ListItem()
  {
    Value = ...
    Text = ...
    Selected = selectedRegions.Contains(r);
  } into item
  order by item.Text
  select item;

lbxRegions.Items.AddRange(allItems.ToArray()) 

AddRange takes IEnumerable<T>, so the call to ToArray is not needed.

David B
This certainly feels more clean and efficient. But strangely enough this doesn't produce the same result. The Contains method always returns false. I am using the default EqualityComparer, same as I did with when I used Except(), but am getting different results. For example, the following expression returns false in the debugger even though the tested-for XElement is definitely present in the collection: selectedRegions.Contains(New XElement("region", New XAttribute("code", "AK")) With {.Value = "ALASKA"}). Any ideas?
Antony Highsky
Check the namespaces?
David B
I didn't see any problems w/ namespaces. So I just created my own EqualityComparer class, and that worked. Thanks for your input.
Antony Highsky