2014-12-12 5 views
1

listbox1 항목과 listbox2 항목을 비교하려고합니다. 중복 된 항목을 제거하려고합니다.listbox1 항목을 listbox2 항목과 비교하고 중복 항목을 제거하십시오.

에 ListBox1는 "링크 1 링크 2 LINK3 link4 link5" '에 ListBox1 다운로드 항목 목록이

listbox2이 포함되어있다 "link9 link5 LINK3" 'listbox2 "LINK3"와 "link5"때문에 항목 목록

을 다운로드 포함 listbox2에 이미 있습니다. listbox1에서 제거하고 싶습니다.

도와주세요.

아래 코드는 작동하지 않습니다.

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

당신은'listbox2.Items'을 통해 반복해야합니다. – Bharadwaj

답변

1

그 Listbox2에 이미있는 Listbox1에서 항목을 제거하려고합니다. 그런 다음 아래 코드를 사용하십시오.

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

여기 Listbox2의 모든 항목을 반복하여 Listbox1에서 제거합니다.

+0

네, 아주 잘 작동합니다. 고맙습니다. – user1785594

+0

답변으로 받아 들일 수 있습니다. – prem

1

하나의 루프로이 작업을 수행 할 수 있습니다. 미안 해요, 난 단지 C#을하지 VB.NET 말을하지만, 개념은 명확합니다 : 또한

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

, 당신은 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); 
} 
0

같은 문제에 대한 또 다른 접근 방식 : 일반 세트를 확인하고 다음

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

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

당신은 또한 다음과 같이 사용할 수있는 첫 번째 목록 상자의 Items 컬렉션에서 제거 :에이 개 목록 상자에서 별개의 항목을 나열 목록 상자

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) 
관련 문제