목록을 비우고 싶습니다. 그렇게하는 방법?
답변
정말 쉽습니다 :
myList.Clear();
답변
“목록”이를 의미하는 List<T>
경우 Clear 메서드가 원하는 것입니다.
List<string> list = ...;
...
list.Clear();
이러한 사항에 대해 MSDN 문서를 검색하는 습관을 가져야합니다.
해당 유형의 다양한 부분에 대한 문서를 빠르게 검색하는 방법은 다음과 같습니다.
- List Class-
List<T>
클래스 자체를 제공합니다 ( 시작해야 할 곳입니다 ). - List.Clear Method -Clear 메소드에 대한 문서를 제공합니다.
- List.Count 속성-Count 속성에 대한 설명서를 제공합니다.
이러한 Google 쿼리는 모두 링크 번들을 나열하지만 일반적으로 각 경우에 Google이 제공하는 첫 번째 링크를 원합니다.
답변
대체 답변을 제공하려면 (누가 5 개의 동일한 답변이 필요합니까?) :
list.Add(5);
// list contains at least one element now
list = new List<int>();
// list in "list" is empty now
이전 목록에 대한 다른 모든 참조는 삭제되지 않았습니다 (상황에 따라 원하는 것일 수 있음). 또한 성능 측면에서 일반적으로 약간 느립니다.
답변
옵션 # 1 : Clear () 함수를 사용 하여 List<T>
용량 을 비우고 유지합니다.
-
Count는 0으로 설정되고 컬렉션 요소에서 다른 개체에 대한 참조도 해제됩니다.
-
용량은 변경되지 않습니다.
옵션 # 2- Clear () 및 TrimExcess () 함수를 사용 List<T>
하여 초기 상태 로 설정 합니다.
-
Count는 0으로 설정되고 컬렉션 요소에서 다른 개체에 대한 참조도 해제됩니다.
-
빈 항목을 트리밍하면
List<T>
목록의 용량이 기본 용량으로 설정됩니다.
정의
개수 = 실제로있는 요소의 수List<T>
용량 = 내부 데이터 구조가 크기를 조정하지 않고 보유 할 수있는 총 요소 수입니다.
Clear () 만
List<string> dinosaurs = new List<string>();
dinosaurs.Add("Compsognathus");
dinosaurs.Add("Amargasaurus");
dinosaurs.Add("Deinonychus");
Console.WriteLine("Count: {0}", dinosaurs.Count);
Console.WriteLine("Capacity: {0}", dinosaurs.Capacity);
dinosaurs.Clear();
Console.WriteLine("\nClear()");
Console.WriteLine("\nCount: {0}", dinosaurs.Count);
Console.WriteLine("Capacity: {0}", dinosaurs.Capacity);
Clear () 및 TrimExcess ()
List<string> dinosaurs = new List<string>();
dinosaurs.Add("Triceratops");
dinosaurs.Add("Stegosaurus");
Console.WriteLine("Count: {0}", dinosaurs.Count);
Console.WriteLine("Capacity: {0}", dinosaurs.Capacity);
dinosaurs.Clear();
dinosaurs.TrimExcess();
Console.WriteLine("\nClear() and TrimExcess()");
Console.WriteLine("\nCount: {0}", dinosaurs.Count);
Console.WriteLine("Capacity: {0}", dinosaurs.Capacity);
답변
당신은 할 수 있습니다
var list = new List<string>();
list.Clear();
답변
명확한 방법을 사용할 수 있습니다.
List<string> test = new List<string>();
test.Clear();
답변
목록에 Clear () 함수가 필요합니다.
List<object> myList = new List<object>();
myList.Add(new object()); // Add something to the list
myList.Clear() // Our list is now empty