List 다중 삭제
이번 포스팅은 C#에서 List의 요소를 다중 삭제할 수 있는 몇 가지 방법을 소개합니다.
방법 1. 특정 조건을 만족하는 요소 삭제
List 클래스에서 제공하는 RemoveAll() 메서드를 사용하여 특정 조건을 만족하는 요소들을 제거할 수 있습니다.
public int RemoveAll (Predicate<T> match);
RemoveAll() 메서드는 특정 조건을 만족하는 요소를 제거하고 제거된 요소의 수를 반환합니다.
다음 예제는 int 타입의 List에서 3 이하인 요소들을 제거합니다.
class Program
{
static void Main(string[] args)
{
List<int> intList = new List<int>() { 1, 2, 3, 4, 5};
int removeCount = 0;
Console.WriteLine("[삭제 전]");
Console.WriteLine(String.Join(", ", intList));
removeCount = intList.RemoveAll(num => num <= 3);
Console.WriteLine("\n[삭제 후]");
Console.WriteLine(String.Join(", ", intList));
Console.WriteLine("\n[삭제된 요소의 개수]");
Console.WriteLine(removeCount);
}
}
[실행 결과]
[삭제 전]
1, 2, 3, 4, 5
[삭제 후]
4, 5
[삭제된 요소의 개수]
3
RemoveAll() 메서드에 다중 조건문을 전달할 수 있습니다.
다음 예제는 int 타입의 List에서 4 보다 작은 요소이며, 2로 나누었을 때 나머지가 1인 요소를 제거합니다.
class Program
{
static void Main(string[] args)
{
List<int> intList = new List<int>() { 1, 2, 3, 4, 5};
int removeCount = 0;
Console.WriteLine("[삭제 전]");
Console.WriteLine(String.Join(", ", intList));
removeCount = intList.RemoveAll(num => num < 4 && num % 2 == 1);
Console.WriteLine("\n[삭제 후]");
Console.WriteLine(String.Join(", ", intList));
Console.WriteLine("\n[삭제된 요소의 개수]");
Console.WriteLine(removeCount);
}
}
[실행 결과]
[삭제 전]
1, 2, 3, 4, 5
[삭제 후]
2, 4, 5
[삭제된 요소의 개수]
2
방법 2. 인덱스 범위로 삭제
또 다른 방법으로 List 클래스에서 제공하는 RemoveRange() 메서드를 사용하여 특정 범위에 해당하는 요소들을 제거할 수 있습니다.
public void RemoveRange (int index, int count);
RemoveRange() 메서드는 시작 위치(index)부터 특정 개수(count)만큼 요소를 제거합니다. 반환 결과는 없습니다.
다음 예제는 int 타입의 List에서 2번째 인덱스부터 3개의 요소를 제거합니다.
class Program
{
static void Main(string[] args)
{
List<int> intList = new List<int>() { 1, 2, 3, 4, 5, 6, 7};
Console.WriteLine("[삭제 전]");
Console.WriteLine(String.Join(", ", intList));
intList.RemoveRange(2, 3);
Console.WriteLine("\n[삭제 후]");
Console.WriteLine(String.Join(", ", intList));
}
}
[실행 결과]
[삭제 전]
1, 2, 3, 4, 5, 6, 7
[삭제 후]
1, 2, 6, 7
방법 3. 다른 List에 존재하는 요소를 삭제
두 개의 List에서 동일한 값을 제고하고 싶은 경우 LINQ에서 제공하는 Except() 메서드를 사용할 수 있습니다.
먼저, LINQ에서 제공하는 기능을 사용하기 위해 다음 네임스페이스를 추가합니다.
using System.Linq;
Except() 메서드는 배열 또는 컬렉션과 같은 데이터 집합의 차집합을 반환하며, 원본 데이터를 변경하지 않습니다.
public static IEnumerable<TSource> Except<TSource>(
this IEnumerable<TSource> first,
IEnumerable<TSource> second);
Except() 메서드의 반환 타입은 IEnumerable<TSource>이므로 List로 변환하기 위해 ToList() 메서드를 호출합니다.
다음 예제는 intList에서 removeList와 동일한 값을 가지는 요소를 제거하고 새로운 List를 생성합니다.
class Program
{
static void Main(string[] args)
{
List<int> intList = new List<int>() { 1, 2, 3, 4, 5, 6, 7};
List<int> removeList = new List<int> { 2, 5 };
Console.WriteLine("[삭제 전 원본 데이터(intList)]");
Console.WriteLine(String.Join(", ", intList));
List<int> result = intList.Except(removeList).ToList();
Console.WriteLine("\n[삭제 후 원본 데이터(intList)]");
Console.WriteLine(String.Join(", ", intList));
Console.WriteLine("\n[Except() 메서드 반환 결과(result)]");
Console.WriteLine(String.Join(", ", result));
}
}
[실행 결과]
[삭제 전 원본 데이터(intList)]
1, 2, 3, 4, 5, 6, 7
[삭제 후 원본 데이터(intList)]
1, 2, 3, 4, 5, 6, 7
[Except() 메서드 반환 결과(result)]
1, 3, 4, 6, 7
방법 4. 모두 삭제
List의 모든 요소를 제거하고 싶은 경우 List의 Clear() 메서드를 사용합니다.
public void Clear ();
다음 예제는 Clear() 메서드를 호출하여 모든 요소를 제거합니다.
class Program
{
static void Main(string[] args)
{
List<int> intList = new List<int>() { 1, 2, 3, 4, 5, 6, 7};
Console.WriteLine("[삭제 전]");
Console.WriteLine(String.Join(", ", intList));
intList.Clear();
Console.WriteLine("\n[삭제 후]");
Console.WriteLine(String.Join(", ", intList));
}
}
[실행 결과]
[삭제 전]
1, 2, 3, 4, 5, 6, 7
[삭제 후]
'C#' 카테고리의 다른 글
[C#]Dictionary 콘솔에 출력하는 방법 (0) | 2022.08.29 |
---|---|
[C#]List의 타입을 변경하는 방법 (0) | 2022.08.28 |
[C#]Stack 특정 값 존재하는지 확인하는 방법 (0) | 2022.08.28 |
[C#]List 마지막 요소 제거 (0) | 2022.08.28 |
[C#]HashSet 반복문 사용 방법 (0) | 2022.08.23 |
댓글