Computer >> 컴퓨터 >  >> 프로그램 작성 >> C#

C# 배열에서 요소를 삭제/제거하는 방법은 무엇입니까?

<시간/>

C# 배열에서 요소를 삭제하려면 사용자가 요소를 삭제하려는 위치에서 요소를 이동합니다.

여기, 먼저 5개의 요소가 있습니다 -

int[] arr = new int[5] {35, 50, 55, 77, 98};

이제 두 번째 위치에서 요소를 삭제해야 한다고 가정해 보겠습니다. 즉, 변수 "pos =2"가 설정되어 지정된 위치 이후의 요소를 이동하기 위해 -

// Shifting elements
for (i = pos-1; i < 4; i++) {
   arr[i] = arr[i + 1];
}

이제 아래의 전체 코드와 같이 결과를 표시하십시오.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Demo {
   class Program {
      static void Main() {
         int i = 0;
         int pos;
         int[] arr = new int[5] {35, 50, 55, 77, 98};

         Console.WriteLine("Elements before deletion:");
         for (i = 0; i < 5; i++) {
            Console.WriteLine("Element[" + (i) + "]: "+arr[i]);
         }

         // Let's say the position to delete the item is 2 i.e. arr[1]
         pos = 2;
         // Shifting elements
         for (i = pos-1; i < 4; i++) {
            arr[i] = arr[i + 1];
         }
         Console.WriteLine("Elements after deletion: ");
         for (i = 0; i < 4; i++) {
            Console.WriteLine("Element[" + (i + 1) + "]: "+arr[i]);
         }
         Console.WriteLine();
      }
   }
}

출력

Elements before deletion:
Element[0]: 35
Element[1]: 50
Element[2]: 55
Element[3]: 77
Element[4]: 98
Elements after deletion:
Element[1]: 35
Element[2]: 55
Element[3]: 77
Element[4]: 98