user1785594
user1785594

Reputation:

Compare the listbox1 items to the listbox2 items and remove duplicates

I'm trying to compare the listbox1 items to the listbox2 items then remove the duplicated ones.

listbox1 contains "link1 link2 link3 link4 link5" 'listbox1 is download items list

listbox2 contains "link9 link5 link3" 'listbox2 is downloaded items list

Since "link3" and "link5" already exists in the listbox2, I want to remove them from the listbox1.

Please help me.

Code below doesn't work.

If listbox1.Items.Contains(listbox2.Items) Then
        listbox1.Items.Remove(listbox2.Items)
end if

Upvotes: 1

Views: 2036

Answers (4)

Thorsten Dittmar
Thorsten Dittmar

Reputation: 56697

You could do this with one loop. Sorry, I only speak C#, not VB.NET, but the concept will be clear:

foreach (var item2 in listbox2.Items)
{
    if (listbox1.Items.Contains(item2))
        listbox1.Items.Remove(item2);
}

Also, you could try this with LINQ:

foreach (var item in listbox2.Items)
{
    var inOtherList = (from it1 in listbox1.Items where it1.Equals(item) select it1);
    foreach (var item in inOtherOtherList)
        listbox1.Items.Remove(item);
}

Upvotes: 1

user4281510
user4281510

Reputation:

You can use like this also: to list distinct items from two list boxes into a listbox

  ListBox1.Items.AddRange(ListBox2.Items)
  Dim DistinctObj = (From LBI As Object In ListBox1.Items Distinct Select LBI).Cast(Of String)().ToArray
  ListBox1.Items.Clear()
  ListBox2.Items.Clear()
  ListBox1.Items.AddRange(DistinctObj)

Upvotes: 0

Steve
Steve

Reputation: 216293

Another approach to the same problem: Identify the common set and then remove it from the Items collection of the first listbox

Dim common = listbox1.Items.Cast(Of string)().
                      Intersect(listbox2.Items.Cast( Of string)()).
                      ToList()

for each x in common
    listbox1.Items.Remove(x)
Next

Upvotes: 0

prem
prem

Reputation: 3538

What I understand from your sample code that you want to remove items from Listbox1 which already exist in Listbox2. Then use the code below.

 For Each itm In ListBox2.Items
      If ListBox1.Items.Contains(itm) Then ListBox1.Items.Remove(itm)
 Next

Here we are iterating through all the items of Listbox2 and removing them from Listbox1 in case it exist.

Upvotes: 1

Related Questions