【问题标题】:how to a specific delete line in textbox如何在文本框中删除特定行
【发布时间】:2013-08-08 13:07:57
【问题描述】:

假设多行文本框中的一个段落包含:

stringrandom@good
stringra12312@good
stringr2a123@bad
strsingra12312@good
strinsgr2a123@bad

我想产生这样的输出:

stringrandom@good
stringra12312@good
strsingra12312@good

我尝试过使用

  If TextBox1.Lines.Count > 2 Then
      Dim newList As List(Of String) = TextBox1.Lines.ToList
      If newList.Contains("@bad") Then
          newList.RemoveAt(newList.Item(newList.Contains("@bad")))
      End If

      TextBox1.Lines = newList.ToArray
  End If

它不起作用,有人知道解决方法吗?

【问题讨论】:

  • 对于未来的问题,请始终定义“不起作用”。这个关键短语很常见,而且不言自明。

标签: .net arrays vb.net string linq


【解决方案1】:

您可以使用 LINQ 来查询列表。

If TextBox1.Lines.Count > 2 Then
    Dim newList As List(Of String) = TextBox1.Lines.ToList
    newList = newList.Where(Function(x) Not x.Contains("bad")).ToList
End If

事实上你并不需要 If 语句:

Dim newList As List(Of String) = TextBox1.Lines.ToList
newList = newList.Where(Function(x) Not x.Contains("bad")).ToList

您甚至可以通过将 LINQ 直接应用于 TextBox 来更简单:

Dim newList As List(Of String) = TextBox1.Lines _
                                 .ToList _
                                 .Where(Function(x) Not x.Contains("bad")) _
                                 .ToList

【讨论】:

    【解决方案2】:

    另一种选择是 (C#);

    const string mail = "stringrandom@good";
    const string mail1 = "stringra12312@good";
    const string mail2 = "stringr2a123@bad";
    const string mail3 = "strsingra12312@good";
    const string mail4 = "strinsgr2a123@bad";
    
    var mails = new string[] { mail, mail1, mail2, mail3, mail4 }; //List of addresses
    
    var x = mails.Where(e => e.Contains("good")).ToList(); //Fetch where the list contains good
    

    或者在 VB 中

    Dim x = mails.Where(Function(e) e.Contains("good")).ToList()
    

    【讨论】:

      【解决方案3】:

      您可以尝试使用正则表达式 (System.Text.RegularExpressions)。试试这个:

      Dim lines = textBox1.Lines _
          .Where(Function(l) Not Regex.Match(l, "\w*@bad").Success) _
          .ToList()
      

      【讨论】:

        【解决方案4】:

        你一开始就很接近。请改用 FindIndex。

          If TextBox1.Lines.Count > 2 Then
              Dim newList As List(Of String) = TextBox1.Lines.ToList
              If newList.Contains("@bad") Then
                  newList.RemoveAt(newList.FindIndex(Function(x) x.Contains("@bad")))
              End If
        
              TextBox1.Lines = newList.ToArray
          End If
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2013-04-04
          • 2021-03-24
          • 2020-08-08
          • 1970-01-01
          相关资源
          最近更新 更多