sourcetip

VB.NET의 배열에서 항목을 삭제하려면 어떻게 해야 합니까?

fileupload 2023. 6. 2. 21:16
반응형

VB.NET의 배열에서 항목을 삭제하려면 어떻게 해야 합니까?

VB.NET의 배열에서 항목을 삭제하려면 어떻게 해야 합니까?

Heinzi가 말했듯이, 배열은 고정된 크기를 가집니다.항목을 '제거'하거나 '크기 조정'하려면 원하는 크기로 새 배열을 만들고 필요한 항목을 적절하게 복사해야 합니다.

배열에서 항목을 제거하는 코드는 다음과 같습니다.

<System.Runtime.CompilerServices.Extension()> _
Function RemoveAt(Of T)(ByVal arr As T(), ByVal index As Integer) As T()
    Dim uBound = arr.GetUpperBound(0)
    Dim lBound = arr.GetLowerBound(0)
    Dim arrLen = uBound - lBound

    If index < lBound OrElse index > uBound Then
        Throw New ArgumentOutOfRangeException( _
        String.Format("Index must be from {0} to {1}.", lBound, uBound))

    Else
        'create an array 1 element less than the input array
        Dim outArr(arrLen - 1) As T
        'copy the first part of the input array
        Array.Copy(arr, 0, outArr, 0, index)
        'then copy the second part of the input array
        Array.Copy(arr, index + 1, outArr, index, uBound - index)

        Return outArr
    End If
End Function

다음과 같이 사용할 수 있습니다.

Module Module1

    Sub Main()
        Dim arr = New String() {"abc", "mno", "xyz"}
        arr.RemoveAt(1)
    End Sub
End Module

두 요소위의코는두번요제다니거합소)를 제거합니다."mno" [가 1입니다.) [1]의 인덱스를 배열에서 가져옵니다.

확장 방법을 사용하려면 .NET 3.5 이상 버전에서 개발해야 합니다..NET 2.0 또는 3.0을 사용하는 경우 메서드를 다음과 같이 호출할 수 있습니다.

arr = RemoveAt(arr, 1)

이것이 당신이 필요로 하는 것이기를 바랍니다.

갱신하다

ToolMakerSteve의 의견에 따라 테스트를 실행한 후, 초기 코드가 업데이트할 배열을 수정하지 않는 것으로 나타납니다.ByVal함수의 선언에 사용됩니다.를 코쓰는것은를드만하와 같은 으로 쓰는입니다.arr = arr.RemoveAt(1)또는arr = RemoveAt(arr, 1)에서는 수정된 배열을 원래 배열로 재할당하므로 배열을 수정합니다.

배열에서 요소를 제거하기 위한 업데이트된 방법(서브루틴) 아래에서 찾을 수 있습니다.

<System.Runtime.CompilerServices.Extension()> _
Public Sub RemoveAt(Of T)(ByRef arr As T(), ByVal index As Integer)
    Dim uBound = arr.GetUpperBound(0)
    Dim lBound = arr.GetLowerBound(0)
    Dim arrLen = uBound - lBound

    If index < lBound OrElse index > uBound Then
        Throw New ArgumentOutOfRangeException( _
        String.Format("Index must be from {0} to {1}.", lBound, uBound))

    Else
        'create an array 1 element less than the input array
        Dim outArr(arrLen - 1) As T
        'copy the first part of the input array
        Array.Copy(arr, 0, outArr, 0, index)
        'then copy the second part of the input array
        Array.Copy(arr, index + 1, outArr, index, uBound - index)

        arr = outArr
    End If
End Sub

메소드의 용도는 원래와 비슷하지만, 이번에는 반환 값이 없기 때문에 반환 값에서 배열을 할당하려고 하면 아무것도 반환되지 않기 때문에 작동하지 않습니다.

Dim arr = New String() {"abc", "mno", "xyz"}
arr.RemoveAt(1)  ' Output: {"abc", "mno"} (works on .NET 3.5 and higher)
RemoveAt(arr, 1) ' Output: {"abc", "mno"} (works on all versions of .NET fx)
arr = arr.RemoveAt(1)  'will not work; no return value
arr = RemoveAt(arr, 1) 'will not work; no return value

참고:

  1. 제가 는 제 할때이 바로 이기 때문입니다. 왜냐하면 그것은 제 의도를 명확하게 하고 VB.NET이 당신이 할 때 바로 뒤에서 하는 일이기 때문입니다.Redim Preserve을 사용하여 배열을 Redim Preserve공구 제조업체 Steve의 답변을 참조하십시오.

  2. RemoveAt여기에 작성된 메소드는 확장 메소드입니다.그것들이 작동하기 위해서, 당신은 그것들을 a에 붙여넣어야 할 것입니다. 그것들이 VB.NET에 놓이면 그것들은 VB.NET에서 작동하지 않을 것입니다.Class.

  3. 중요 '제거'를 많이 사용하여 어레이를 수정할 경우 다음과 같은 다른 데이터 구조를 사용하는 것이 좋습니다.List(Of T)이 질문에 대한 다른 답변들이 제안한 바와 같이.

그럴수는 없어요.배열 요소를 에 넣으면 최소한 항목을 제거할 수 있습니다.예를 들어, 어레이를 확장할 수 있습니다.ReDim그러나 배열 요소를 만든 후에는 제거할 수 없습니다.이를 위해서는 어레이를 처음부터 다시 구축해야 합니다.

피할 수 있으면 여기서 어레이를 사용하지 말고 다음을 사용하십시오.List.

LINQ를 사용하는 한 줄:

Dim arr() As String = {"uno", "dos", "tres", "cuatro", "cinco"}
Dim indx As Integer = 2
arr = arr.Where(Function(item, index) index <> indx).ToArray 'arr = {"uno", "dos", "cuatro", "cinco"}

첫 번째 요소 제거:

arr = arr.Skip(1).ToArray

마지막 요소 제거:

arr = arr.Take(arr.length - 1).ToArray

삭제 내용에 따라 다릅니다.배열은 크기가 고정되어 있으므로 삭제하는 것은 의미가 없습니다.

i 요소를 입니다.j > i왼쪽으로 한 위치(a[j - 1] = a[j]j 는사용을 사용합니다.Array.Copy그런 다음 ReDim 보존을 사용하여 배열 크기를 조정합니다.

따라서 외부 제약 조건으로 인해 어레이를 사용해야 하는 경우를 제외하고는 항목을 추가하거나 제거하는 데 더 적합한 데이터 구조를 사용하는 것이 좋습니다.예를 들어 List<T>는 내부적으로 배열을 사용하지만 크기 조정 문제 자체를 처리합니다.항목을 제거하는 경우 위에 언급된 알고리즘(ReDim 제외)을 사용하므로 O(n) 연산입니다.

시스템에는 다양한 수집 클래스가 있습니다.컬렉션.다양한 사용 사례에 최적화된 일반 네임스페이스입니다.항목을 자주 제거해야 하는 경우 어레이보다 더 나은 옵션이 많이 있습니다.List<T>).

예, 배열에서 요소를 삭제할 수 있습니다.다음은 필요에 따라 요소를 이동한 다음 배열의 크기를 한 단계 짧게 조정하는 확장 방법입니다.

' Remove element at index "index". Result is one element shorter.
' Similar to List.RemoveAt, but for arrays.
<System.Runtime.CompilerServices.Extension()> _
Public Sub RemoveAt(Of T)(ByRef a() As T, ByVal index As Integer)
    ' Move elements after "index" down 1 position.
    Array.Copy(a, index + 1, a, index, UBound(a) - index)
    ' Shorten by 1 element.
    ReDim Preserve a(UBound(a) - 1)
End Sub

사용 예(색인 0으로 시작하는 배열로 가정):

Dim a() As String = {"Albert", "Betty", "Carlos", "David"}
a.RemoveAt(0)    ' Remove first element => {"Betty", "Carlos", "David"}
a.RemoveAt(1)    ' Remove second element => {"Betty", "David"}
a.RemoveAt(UBound(a))    ' Remove last element => {"Betty"}

첫 번째 또는 마지막 요소를 제거하는 것은 일반적이므로 다음은 편리한 루틴입니다(내 의도를 보다 읽기 쉽게 표현하는 코드가 좋습니다).

<System.Runtime.CompilerServices.Extension()> _
Public Sub DropFirstElement(Of T)(ByRef a() As T)
    a.RemoveAt(0)
End Sub

<System.Runtime.CompilerServices.Extension()> _
Public Sub DropLastElement(Of T)(ByRef a() As T)
    a.RemoveAt(UBound(a))
End Sub

용도:

a.DropFirstElement()
a.DropLastElement()

그리고 Heinzi가 말했듯이, 만약 당신이 이것을 하고 있다면, 가능하다면 List (Of T)를 사용하세요.목록에 이미 "RemoveAt" 하위 루틴과 요소 삽입/삭제에 유용한 다른 루틴이 있습니다.

내가 가장 좋아하는 방법:

Imports System.Runtime.CompilerServices

<Extension()> _
Public Sub RemoveAll(Of T)(ByRef arr As T(), matching As Predicate(Of T))
    If Not IsNothing(arr) Then
        If arr.Count > 0 Then
            Dim ls As List(Of T) = arr.ToList
            ls.RemoveAll(matching)
            arr = ls.ToArray
        End If
    End If
End Sub

그런 다음 코드에서 배열에서 무언가를 제거해야 할 때마다 배열에 있는 특정 값을 가진 개체의 일부 속성으로 제거할 수 있습니다.

arr.RemoveAll(Function(c) c.MasterContactID.Equals(customer.MasterContactID))

또는 제거할 개체를 이미 알고 있는 경우 다음 작업을 수행할 수 있습니다.

arr.RemoveAll(function(c) c.equals(customer))

i삭제할 요소의 인덱스를 나타냅니다.

System.Array.Clear(ArrayName, i, 1)

이것은 게으른 사람의 해결책일 수도 있지만, 0 또는 ""로 값을 재할당하여 제거할 인덱스의 내용을 삭제하고 배열을 다시 만들고 복사하는 대신 빈 배열 요소를 무시하거나 건너뛸 수는 없을까요?

Public Sub ArrayDelAt(ByRef x As Array, ByVal stack As Integer)
    For i = 0 To x.Length - 2
        If i >= stack Then
            x(i) = x(i + 1)
            x(x.Length-1) = Nothing
        End If
    Next
End Sub

이것을 먹어보세요.

이게 더 복잡한 것 같은데요

    Dim myArray As String() = TextBox1.Lines
    'First we count how many null elements there are...
    Dim Counter As Integer = 0
    For x = 0 To myArray.Count - 1
        If Len(myArray(x)) < 1 Then
            Counter += 1
        End If
    Next
    'Then we dimension an array to be the size of the last array
    'minus the amount of nulls found...
    Dim tempArr(myArray.Count - Counter) As String

    'Indexing starts at zero, so let's set the stage for that...
    Counter = -1

    For x = 0 To myArray.Count - 1
        'Set the conditions for the new array as in
        'It .contains("word"), has no value, length is less than 1, ect.
        If Len(myArray(x)) > 1 Then
            Counter += 1
            'So if a value is present, we move that value over to
            'the new array.
            tempArr(Counter) = myArray(x)
        End If
    Next

이제 임시 Arr을 원래대로 돌려보내거나 필요한 일을 할 수 있습니다.

텍스트 상자 1.선 = tempArr(이제 빈 선이 있는 텍스트 상자가 있음)

배열이 문자열 배열인 경우 다음을 수행할 수 있습니다.

AlphaSplit = "a\b\c".Split("\")
MaxIndex   = AlphaSplit.GetUpperBound(0)
AlphaSplit = AlphaSplit.Where(Function(item, index) index <> MaxIndex).ToArray
AlphaJoin  = String.Join("\", PublishRouteSplit)

이 방법은 어떻습니까?tempArray tempArray가 어레이에 대해 최소 1개의 요소를 더 적게 포함해야 하는 메서드를 가져옵니다(: permArray). 메서드가 취해야 하는 정수 매개 변수(원하지 않는 요소의 인덱스가 될 것)를 생략합니다.인덱스permArray

메소드에서 요소를 제외한 모든 요소를 위치 생략으로 복사permArray에서 tempArray로 인덱스 생성

메서드는 tempArray를 반환하므로 메서드를 사용하여 permArray를 업데이트합니다.

여기에 토막글이 있습니다.

Function updateArray(ommitIndex As Integer, array() As String) As Array
    Dim tempArray(array.Length - 2) As String
    Dim counter As Integer = 0

    For i As Integer = 0 To (array.Length - 1)
        If (i <> ommitIndex) Then
            tempArray(counter) = array(i)
            counter += 1
        End If
    Next

    Return tempArray
End Function

언급URL : https://stackoverflow.com/questions/3448103/how-can-i-delete-an-item-from-an-array-in-vb-net

반응형