Get Selected Items From Multiple ASP.NET ListBox and Merge them using LINQ

A few questions floating around on the forums is how to get the selected items from two different list boxes and merge them into one result. LINQ is a good technology to handle this. Here's the code to do this in LINQ.

Add two list boxes to your page:

<asp:ListBox ID="ListBox1" runat="server" SelectionMode="Multiple">
<
asp:ListItem Text="One" Value="One" />
<
asp:ListItem Text="Two" Value="Two" />
<
asp:ListItem Text="Three" Value="Three" />
<
asp:ListItem Text="Four" Value="Four" />
<
asp:ListItem Text="Five" Value="Five" />
<
asp:ListItem Text="Six" Value="Six" />
<
asp:ListItem Text="Seven" Value="Seven" />
</
asp:ListBox>

<
asp:ListBox ID="ListBox2" runat="server" SelectionMode="Multiple">
<
asp:ListItem Text="One" Value="One" />
<
asp:ListItem Text="Two" Value="Two" />
<
asp:ListItem Text="Three" Value="Three" />
<
asp:ListItem Text="Four" Value="Four" />
<
asp:ListItem Text="Five" Value="Five" />
<
asp:ListItem Text="Six" Value="Six" />
<
asp:ListItem Text="Seven" Value="Seven" />
</
asp:ListBox>



And here is the LINQ query

C#

var query = from p in ListBox1.Items.OfType<ListItem>()
.Concat(ListBox2.Items.OfType<ListItem>())
.Where(o => o.Selected)
select new
{
Text = p.Text
};

foreach (var item in query)
{
// print item
}

VB.NET

Protected Sub Button1_Click(ByVal sender As Object, ByVal e As EventArgs) _
Handles Button1.Click
Dim query = From p In ListBox1.Items.OfType(Of ListItem)() _
.Concat(ListBox2.Items.OfType(Of ListItem)()) _
.Where(Function(o) o.Selected) _
Select New With {Key .Text = p.Text}

For Each item In query
' Print item.Text
Next item

End Sub

Thanks to David Anton for translating the code to VB.NET

OUTPUT

image






About The Author

Malcolm Sheridan is a Microsoft awarded MVP in ASP.NET and regular presenter at conferences and user groups throughout Australia. Being an ASP.NET Insider, his focus is on web technologies and has been for the past 10 years. He loves working with ASP.NET MVC these days and also loves getting his hands dirty with JavaScript. He also blogs regularly at DotNetCurry.com. Follow him on twitter @malcolmsheridan

3 comments:

Anonymous said...

One thing to consider is how you want the "Merge" to work when the same value is selected. If you select "Two" in both lists, should it be duplicated in your result set? Using Concat, it will. If you want to eliminate the duplicate, you could consider using the set based Union method instead.

Norah said...

I think very nice suggestion by Jim

Malcolm Sheridan said...

@Jim
How that works is really up to the developer. If they're not concerned about duplicates then the basic code will work. If they want duplicates removed then your suggestion would be the way to go.