【问题标题】:Remove Duplicate Lines completely完全删除重复行
【发布时间】:2020-11-29 03:28:30
【问题描述】:

我在网上到处搜索 rn

我只需要一个代码来删除我在我的字符串/列表/richtextbox 中的所有重复项 这是我想要的一个例子:

我接受 C# 和 VB.NET 代码

发件人:

asd asd djsdjjd 252

到:

djsdjjd 252

我尝试过的代码:

Dim liness As New List(Of String)(RichTextBox1.Lines)
Dim lines2() As String = (From s As String In liness).Distinct.ToArray
RichTextBox1.Lines = lines2
Dim count As Integer = liness.Count - lines2.Length
MessageBox.Show(count.ToString)

&

Dim lines1 As New List(Of String)(RichTextBox1.Lines)
Dim testint As Integer
For i As Integer = lines1.Count - 1 To 1 Step -1
    If lines1(i) = lines1(i - 1) Then
        lines1.RemoveAt(i)
        lines1.RemoveAt(i - 1)
        i = -1
    End If
Next
MsgBox("")
RichTextBox1.Lines = lines1.ToArray

【问题讨论】:

    标签: vb.net duplicates removeall


    【解决方案1】:

    有很多方法可以做到这一点。这只是其中之一:

    Dim linesByCount As New Dictionary(Of String, Integer)
    
    For Each line In RichTextBox1.Lines
        If linesByCount.ContainsKey(line) Then
            lineByCount(line) += 1
        Else
            lineByCount.Add(line, 1)
        End If
    Next
    
    Dim uniqueLines As New List(Of String)
    
    For Each line In linesByCount.Keys
        If linesByCount(line) = 1 Then
            uniqueLines.Add(line)
        End If
    Next
    
    RichTextBox1.Lines = lines.ToArray()
    

    这是使用 LINQ 的另一个选项:

    RichTextBox1.Lines = RichTextBox1.Lines.
                                      GroupBy(Function(s) s).
                                      Where(Function(g) g.Count() = 1).
                                      Select(Function(g) g.Key).
                                      ToArray()
    

    无论您选择哪个选项,诀窍都是先获取每个值的计数,然后再删除任何内容。否则,您将不会知道重复的最后一个实例实际上是重复的。也就是说,这些选项都没有真正删除任何东西。他们创建了一个包含每个项目计数的列表,然后他们挑选出计数为 1 的项目并将它们添加到一个新列表中。

    这是另一种选择:

    Dim lines = RichTextBox1.Lines
    
    RichTextBox1.Lines = lines.Where(Function(s) Array.IndexOf(lines, s) = Array.LastIndexOf(lines, s)).ToArray()
    

    【讨论】:

      【解决方案2】:

      或者你也可以使用:

      Dim newLines() As String = liness.Where(Function(s) liness.Where(Function(s1) s = s1).Count = 1).ToArray
      

      【讨论】:

        猜你喜欢
        • 2011-03-21
        • 2022-11-14
        • 2021-12-05
        • 2021-04-30
        • 2013-08-02
        • 1970-01-01
        • 2016-01-04
        • 2021-03-07
        • 2020-07-27
        相关资源
        最近更新 更多