比较两个列表框的值,并将非等效值添加到第三个列表框

时间:2016-06-23 17:32:31

标签: vb.net listbox

我对编程的了解不是很广泛,但我刚刚完成了计算机工程高等教育的第二年,并参加了一些低级编程课程。

在Visual Basic中,我无法比较两个ListBox控件的值,并将不相同的值放入另一个ListBox

我需要将ListBox2的项目与ListBox1的项目进行比较,如果ListBox2中有任何项目不在ListBox1中,请将它们添加到ListBox3 {1}}。我无需在ListBox1中找到ListBox2以外的项目。我不能使用循环来根据索引比较它们的值,因为这些列表的名称将不断添加和删除。我也无法对这些ListBox进行排序。

有一个C#示例,我发现here 使用LINQ(我真的不知道那是什么)比较列表,然后将结果添加到TextBox控件。但是,我需要知道如何将它们添加到ListBox而不是TextBox

[编辑]我试过的例子就是:

Dim result As List(Of String) = (From s1 As String In Me.ListBox1.Items Where Not Me.ListBox2.Items.Contains(s1) Select s1).ToList()
Me.TextBox1.Text = String.Join(Environment.NewLine, result)

2 个答案:

答案 0 :(得分:0)

我想我找到了解决方案:

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    ListBox3.Items.Clear()
    Dim result As List(Of String) = (From s1 As String In Me.ListBox2.Items Where Not Me.ListBox1.Items.Contains(s1) Select s1).ToList()
    For Each l In result
        ListBox3.Items.Add(l)
    Next
End Sub

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    Dim result As List(Of String) = (From s1 As String In Me.ListBox2.Items Where Not Me.ListBox1.Items.Contains(s1) Select s1).ToList()
    For Each l In result
        If Not ListBox3.Items.Contains(l) Then
            ListBox3.Items.Add(l)
        End If
    Next
End Sub

尝试哪种方式最适合你:)

答案 1 :(得分:0)

ReallyCoolType tStatArray = datatList.toArray();  // didn't see a type, so I made up one
int endOf = tStatArray.length; // why declare this but never use it? Not really needed, but...
SortedSet<Object> set = new TreeSet<Object>();
for (int i = 0; i < endOf; i++) {
    // note the use of i, not the undeclared j
    if( !contains(set, tStatArray[i] )
    {
        set.add(tStatArray[i]);
    }
}

// and you can keep printing it out if you want...
Iterator it = set.iterator();
while(it.hasNext()) {
    System.out.println(it.next());
}

...

public bool contains( ReallyCoolType[] paramArray, ReallyCoolType findMe ) {
    bool found = false;
    for (reallyCoolType param : paramArray) {
        if( reallyCoolType.Equals(param, findMe) {
            found = true;
            break;
        }
    }
    return found;
}

我相信这可能是你正在寻找的。它的作用是将 Dim one As ListBox = New ListBox() Dim two As ListBox = New ListBox() Dim three As ListBox = New ListBox() Dim unique As Boolean = True For i As Integer = 0 To one.Items.Count For j As Integer = 0 To two.Items.Count If (one.Text = two.Text) Then unique = False Else two.SelectedIndex = j End If Next If (unique) Then three.Items.Add(one.Text) Else one.SelectedIndex = i unique = True End If Next 中的每个值与Listbox one中的所有值进行比较,如果看到某个值是重复的,则Listbox two标志Boolean将切换为false并且商品未添加到unique