Monday, August 17, 2009

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

I recently did a short article on Get Selected Items From Multiple ASP.NET ListBox and Merge the results using LINQ. A user pointed out what if you wanted only the unique values from each list. Well here are two options to do that.

Add two list boxes and a button control to your page:
























onclick="Button1_Click" />


You have two options to select unique values from both the listboxes. You can use Distinct or Union. Here’s the code for both.
Distinct

C#

protected void Button1_Click(object sender, EventArgs e)
{
var distinct = from p in ListBox1.Items.OfType()
.Concat(ListBox2.Items.OfType())
.Where(o => o.Selected)
.Distinct()
select new
{
Text = p.Text
};

foreach (var item in distinct)
{
Response.Write(item.Text + "
");
}
}

VB.NET

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

For Each item In distinct
Response.Write(item.Text & "
")
Next item
End Sub

Union

C#

protected void Button1_Click(object sender, EventArgs e)
{
var list1 = from p in ListBox1.Items.OfType()
.Where(o => o.Selected)
select new
{
Text = p.Text
};

var list2 = from p in ListBox2.Items.OfType()
.Where(o => o.Selected)
select new
{
Text = p.Text
};

var unique = list1.Union(list2);

foreach (var item in unique)
{
Response.Write(item.Text + "
");
}
}

VB.NET

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

Dim list2 = _
From p In ListBox2.Items.OfType(Of ListItem)() _
.Where(Function(o) o.Selected) _
Select New With {Key .Text = p.Text}

Dim unique = list1.Union(list2)

For Each item In unique
Response.Write(item.Text & "
")
Next item
End Sub

OUTPUT

image

No comments:

Post a Comment