开发者

Most efficient way to bind a Listbox with SelectionMode=Multiple

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 of开发者_如何学Pythonf" 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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜