给出单词列表......
Word Word Base Ball Ball Apple Cardinal
我如何去除所有出现的“Word”和“Ball”?我做了一些研究并找到了list.RemoveAll
函数。我对如何在字符串列表上实现它感到困惑。将列表转换为数组会更好吗?
Public Function getListOfWords() As String()
listOfWords.RemoveAll("the")
Dim arrayA() As String = listOfWords.ToArray
Return arrayA
End Function
答案 0 :(得分:3)
这是你可以在List(Of String)上使用RemoveAll的方法
Dim words = New List(Of String) From { "Word","Word","Base","Ball","Ball","Apple","Cardinal"}
Dim wordsRemoved = words.RemoveAll(Function(s) s = "Word" OrElse s = "Ball")
Console.WriteLine(wordsRemoved)
For Each s in words
Console.WriteLine(s)
Next
在此上下文中,RemoveAll需要一个接收字符串并返回布尔值(A Predicate(Of T))的函数。函数通过重复调用逐个接收序列中包含的元素,并返回true以删除元素,或者返回false以保留元素
答案 1 :(得分:1)
我知道它的回答和接受。但就可扩展性而言,bool谓词似乎有点硬编码,即如果你要删除的单词是" Word"," Ball"," Apple&# 34 ;?现在必须在代码中更改谓词。我想你可以在谓词中聚合代码,但现在事情变得愚蠢了。
您可能还认为问题是需要LEFT OUTER JOIN来解决它,这将接受排除列表中的任意数量的元素。这是一个你可以使用的功能
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/js/bootstrap.min.js"></script>
<form class="form-horizontal" id="formTest">
<div class="row">
<div class="col-xs-6">
<div class="form-group">
<label for="lblFirstName" class="control-label col-xs-4">First Name</label>
<div class="col-xs-8">
<input type="textbox" class="form-control" />
</div>
</div>
</div>
<div class="col-xs-6">
<div class="form-group">
<label for="lblLastname" class="control-label col-xs-4">Last Name</label>
<div class="col-xs-8">
<input type="textbox" class="form-control" />
</div>
</div>
</div>
</div>
<div class="row">
<div class="col-xs-12">
<div class="form-group">
<label for="lblComments" class="control-label col-xs-2">Comments</label>
<div class="col-xs-10">
<textarea type="textbox" id="Comments" class="form-control"></textarea>
</div>
</div>
</div>
</div>
</form>
现在,您可以在任何数量的列表中包含两个集合而不是两个bool谓词,并调用函数
Public Function getListOfWords(words As IEnumerable(Of String),
wordsToRemove As IEnumerable(Of String)) As String()
Dim wordsRemoved = From word In words
Group Join wordToRemove In wordsToRemove
On word Equals wordToRemove Into Group
From g In Group.DefaultIfEmpty
Where g = ""
Select word
Return wordsRemoved.ToArray()
End Function
答案 2 :(得分:0)
假设重复一个接一个:
Dim s = "Word Word Base Ball Ball Apple Cardinal"
Dim pattern = "(?i)(?'word'[a-z]+)(\s+\k'word')"
Dim s2 = Regex.Replace(s, pattern, "${word}")