从转换为字符串的 ListBox 中删除重复项

Removing a Duplicate Item from ListBox converted into a string

我有一个问题,当我从 ListBox 中取出项目并将它们转换为单行字符串时,它复制了最后一个项目。我的目标是让它只获取 ListBox 中的项目,并将其转换为一行文本,以逗号分隔 (,)。

我花了一些时间,但我在 this thread 上找到了一些代码,大部分都有效,但最后一项在转换为字符串时总是重复。我使用的代码是:

        Dim item As Object
        Dim List As String
      
        ' Other unrelated code

        ' Credit: T0AD - https://www.tek-tips.com/viewthread.cfm?qid=678275
        For Each item In Form1.ListBox1_lstbox.Items
            List &= item & ","
        Next

        'To remove the last comma.
        List &= item.SubString(0, item.Length - 0) 
        ' This is weird, but setting item.Length - 1 actually removes two characters.

        ' Add text to textbox
        TextBox1.Text = List

我觉得它必须处理删除逗号的代码,因为它是 &= 再次调用 item Dim。但我似乎不知道该怎么做。

输出示例如下所示:Item1,Item2,Item3,Item3

当我只想要这个时:Item1,Item2,Item3

你的问题出在这一行上。

List &= item.SubString(0, item.Length - 0)

您正在使用 &=List 添加另一个字符串。您要添加的字符串是 For Each 循环中 item 的最终值。

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    If ListBox1.Items.Count = 0 Then
        MessageBox.Show("There are no items in the list box.")
        Exit Sub
    End If
    Dim List As String = ""
    For Each item In ListBox1.Items
        List &= item.ToString & ","
    Next
    List = List.Substring(0, List.Length - 1)
    TextBox1.Text = List
End Sub

@Andrew Morton 在评论中提供的附加解决方案,不需要 ListBox 包含项目。

TextBox1.Text = String.Join(",", ListBox1.Items.Cast(Of Object))