C#

[C#]List 마지막 요소 제거

DevStory 2022. 8. 28.

List 마지막 요소 제거

이번 포스팅은 C#의 List에서 마지막 요소를 제거하는 몇 가지 방법을 소개합니다.


방법 1. List의 RemoveAt 메서드(권장 방법)

첫 번째 방법으로 ArrayList 클래스에서 제공하는 RemoveAt() 메서드를 사용하여 마지막 요소를 제거할 수 있습니다.

public void RemoveAt(int index);

RemoveAt() 메서드의 매개변수로 인덱스를 전달하면 해당 인덱스에 있는 요소가 제거됩니다.

 

RemoveAt() 메서드의 반환 타입은 void이므로 아무것도 반환하지 않습니다.

class Program
{
  static void Main(string[] args)
  {
    List<int> intList = new List<int>()
    {
      1, 2, 3, 4, 5
    };

    Console.WriteLine("[삭제 전]");
    foreach(int num in intList)
    {
      Console.Write(num + " ");
    }

    intList.RemoveAt(intList.Count - 1);

    Console.WriteLine("\n");
    Console.WriteLine("[삭제 후]");
    foreach (int num in intList)
    {
      Console.Write(num + " ");
    }
  }
}

[실행 결과]

[삭제 전]
1 2 3 4 5

[삭제 후]
1 2 3 4

만약, List가 빈 객체로 할당되어 요소가 존재하지 않는 경우 RemoveAt() 메서드에서 ArgumentOutOfRangeException이 발생합니다.

 

따라서, 다음 소스 코드처럼 List가 null이 아니며, 요소의 개수가 존재하면 RemoveAt() 메서드를 호출하도록 합니다.

class Program
{
  static void Main(string[] args)
  {
    List<int> intList = new List<int>();
    
    if (intList != null && intList.Count > 0)
    {
      intList.RemoveAt(intList.Count - 1);
    }
  }
}

방법 2. List의 RemoveRange 메서드

두 번째 방법으로 List 클래스에서 제공하는 RemoveRange() 메서드를 사용하여 마지막 요소를 제거할 수 있습니다.

public void RemoveRange(int index, int count);

RemoveRange() 메서드는 List 객체의 시작 위치(index)에서 특정 개수(count)만큼 요소를 제거합니다.

 

RemoveRange() 메서드의 반환 타입은 void이므로 아무것도 반환하지 않습니다.

class Program
{
  static void Main(string[] args)
  {
    List<int> intList = new List<int>()
    {
      1, 2, 3, 4, 5
    };

    Console.WriteLine("[삭제 전]");
    foreach(int num in intList)
    {
      Console.Write(num + " ");
    }

    if (intList != null && intList.Count > 0)
    {
      intList.RemoveRange(intList.Count - 1, 1);
    }

    Console.WriteLine("\n");
    Console.WriteLine("[삭제 후]");
    foreach (int num in intList)
    {
      Console.Write(num + " ");
    }
  }
}

[실행 결과]

[삭제 전]
1 2 3 4 5

[삭제 후]
1 2 3 4

방법 3. LINQ의 Take 메서드

세 번째 방법으로 LINQ에서 제공하는 Take() 메서드를 사용하여 마지막 요소가 제거된 새로운 List를 생성할 수 있습니다.

 

먼저, LINQ에서 제공하는 기능을 사용하기 위해 다음 네임스페이스를 추가합니다.

using System.Linq;

Take() 메서드는 배열 또는 컬렉션과 같은 데이터 집합에서 특정 개수만큼 데이터를 가져옵니다.

public static IEnumerable<TSource> Take<TSource>(this IEnumerable<TSource> source, int count);

Take() 메서드의 반환 타입은 List가 아니므로 ToList() 메서드를 호출하여 List로 변환합니다.

 

원본 데이터를 보존하고 싶은 경우 Take() 메서드를 사용할 수 있습니다.

class Program
{
  static void Main(string[] args)
  {
    List<int> intList = new List<int>()
    {
      1, 2, 3, 4, 5
    };
    List<int> newIntList = new List<int>();

    Console.WriteLine("[intList의 요소]");
    foreach(int num in intList)
    {
      Console.Write(num + " ");
    }

    if (intList != null && intList.Count > 0)
    {
      newIntList = intList.Take(intList.Count - 1).ToList();
    }

    Console.WriteLine("\n");
    Console.WriteLine("[newIntList의 요소]");
    foreach (int num in newIntList)
    {
      Console.Write(num + " ");
    }
  }
}

[실행 결과]

[intList의 요소]
1 2 3 4 5

[newIntList의 요소]
1 2 3 4

LINQ에서 제공하는 Take() 메서드에 대한 세부적인 내용은 아래 포스팅에서 확인할 수 있습니다.

 

[C#]LINQ 특정 개수만큼 데이터 가져오기 - Take 메서드

Take 메서드 C#의 Linq는 데이터 집합에서 특정 개수만큼 데이터를 가져오는 Take() 메서드를 제공합니다. 데이터 집합의 처음 위치에서 n개의 데이터를 가져오며, 특정 개수는 Take() 메서드의 매개변

developer-talk.tistory.com


방법 4. LINQ의 SkipLast 메서드

마지막 방법으로 LINQ에서 제공하는 SkipLast() 메서드를 사용하여 마지막 요소가 제거된 새로운 List를 생성할 수 있습니다.

 

SkipLast() 메서드는 데이터 집합 뒤에서 특정 개수의 데이터가 생략된 새로운 데이터 집합을 생성합니다.

public static IEnumerable<TSource> SkipLast<TSource>(
  this IEnumerable<TSource> source, int count);

SkipLast() 메서드의 반환 타입은 List가 아니므로 ToList() 메서드를 호출하여 List로 변환합니다.

 

원본 데이터를 보존하고 싶은 경우 SkipLast() 메서드를 사용할 수 있습니다.

class Program
{
  static void Main(string[] args)
  {
    List<int> intList = new List<int>()
    {
      1, 2, 3, 4, 5
    };
    List<int> newIntList = new List<int>();

    Console.WriteLine("[intList의 요소]");
    foreach(int num in intList)
    {
      Console.Write(num + " ");
    }

    if (intList != null && intList.Count > 0)
    {
      newIntList = intList.SkipLast(1).ToList();
    }

    Console.WriteLine("\n");
    Console.WriteLine("[newIntList의 요소]");
    foreach (int num in newIntList)
    {
      Console.Write(num + " ");
    }
  }
}

[실행 결과]

[intList의 요소]
1 2 3 4 5

[newIntList의 요소]
1 2 3 4
반응형

'C#' 카테고리의 다른 글

[C#]List 다중 삭제  (0) 2022.08.28
[C#]Stack 특정 값 존재하는지 확인하는 방법  (0) 2022.08.28
[C#]HashSet 반복문 사용 방법  (0) 2022.08.23
[C#]HashSet 합치는 방법  (0) 2022.08.22
[C#]HashSet 초기화 방법  (0) 2022.08.21

댓글