从 VB.NET 中的数组中删除元素

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/24001479/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-17 17:38:51  来源:igfitidea点击:

Remove element from an array in VB.NET

vb.net

提问by codematrix

I have below variable.

我有以下变量。

Dim strValues As String() with values "1", "2", "3", "4", "5", "6", "7"

Dim strValues As String() 值为“1”、“2”、“3”、“4”、“5”、“6”、“7”

I want to delete "4" from StrValues based on the string index without knowing the string value in vb.net. How can I do this?

我想根据字符串索引从 StrValues 中删除“4”而不知道 vb.net 中的字符串值。我怎样才能做到这一点?

回答by Daniel

I'd use Linq for simplicity:

为简单起见,我会使用 Linq:

Dim strValues = {"1", "2", "3", "4", "5", "6", "7"}
strValues = strValues.Where(Function(s) s <> "4").ToArray 'Removes all instances

Better yet, use a list:

更好的是,使用列表:

Dim strValues = {"1", "2", "3", "4", "5", "6", "7"}.ToList
strValues.Remove("4") 'Removes first instance of "4" only

If you want to do it by value at index you could do something like the following (though these will remove all instances of the value):

如果您想在索引处按值执行此操作,您可以执行以下操作(尽管这些将删除该值的所有实例):

Dim index = 3
strValues = strValues.Where(Function(s) s <> strValues(index)).ToArray

or

或者

strValues = strValues.Except({strValues(index)}).ToArray

To remove or skip a given index (single instance only), you could do something like this:

要删除或跳过给定的索引(仅限单个实例),您可以执行以下操作:

Dim index = 3
strValues = strValues.Take(index).Concat(strValues.Skip(index + 1)).ToArray

回答by Simcha Khabinsky

 Dim strValues As String() = New String() {"1", "2", "3", "4"}
 Dim strList As List(Of String) = strValues.ToList()
 strList.Remove("4")
 strValues = strList.ToArray()

回答by Anthony Benavente

Depending on what you mean by "delete", you could do a couple of things. First, if you're for a dynamically sized array, you may want to look into the ArrayListor List(of T). This class allows you to add and delete objects to an array while resizing for you if necessary. However, if you literally want to delete it from your array, you can set the value to 0or Nothingor shift all the values in the array after it down one index.

根据“删除”的含义,您可以做几件事。首先,如果您要使用动态大小的数组,您可能需要查看ArrayListor List(of T)。此类允许您在必要时为您调整大小时向数组添加和删除对象。但是,如果您真的想从数组中删除它,您可以将该值设置为0orNothing或将数组中的所有值向下移动一个索引。