List<T> 클래스
정의
중요
일부 정보는 릴리스되기 전에 상당 부분 수정될 수 있는 시험판 제품과 관련이 있습니다. Microsoft는 여기에 제공된 정보에 대해 어떠한 명시적이거나 묵시적인 보증도 하지 않습니다.
인덱스로 액세스할 수 있는 강력한 형식의 개체 목록을 나타냅니다. 목록의 검색, 정렬 및 조작에 사용할 수 있는 메서드를 제공합니다.
generic <typename T>
public ref class List : System::Collections::Generic::ICollection<T>, System::Collections::Generic::IEnumerable<T>, System::Collections::Generic::IList<T>, System::Collections::Generic::IReadOnlyCollection<T>, System::Collections::Generic::IReadOnlyList<T>, System::Collections::IList
generic <typename T>
public ref class List : System::Collections::Generic::ICollection<T>, System::Collections::Generic::IEnumerable<T>, System::Collections::Generic::IList<T>, System::Collections::IList
public class List<T> : System.Collections.Generic.ICollection<T>, System.Collections.Generic.IEnumerable<T>, System.Collections.Generic.IList<T>, System.Collections.Generic.IReadOnlyCollection<T>, System.Collections.Generic.IReadOnlyList<T>, System.Collections.IList
[System.Serializable]
public class List<T> : System.Collections.Generic.ICollection<T>, System.Collections.Generic.IEnumerable<T>, System.Collections.Generic.IList<T>, System.Collections.IList
[System.Serializable]
public class List<T> : System.Collections.Generic.ICollection<T>, System.Collections.Generic.IEnumerable<T>, System.Collections.Generic.IList<T>, System.Collections.Generic.IReadOnlyCollection<T>, System.Collections.Generic.IReadOnlyList<T>, System.Collections.IList
type List<'T> = class
interface ICollection<'T>
interface seq<'T>
interface IEnumerable
interface IList<'T>
interface IReadOnlyCollection<'T>
interface IReadOnlyList<'T>
interface ICollection
interface IList
[<System.Serializable>]
type List<'T> = class
interface IList<'T>
interface ICollection<'T>
interface seq<'T>
interface IList
interface ICollection
interface IEnumerable
[<System.Serializable>]
type List<'T> = class
interface IList<'T>
interface ICollection<'T>
interface IList
interface ICollection
interface IReadOnlyList<'T>
interface IReadOnlyCollection<'T>
interface seq<'T>
interface IEnumerable
[<System.Serializable>]
type List<'T> = class
interface IList<'T>
interface ICollection<'T>
interface seq<'T>
interface IEnumerable
interface IList
interface ICollection
interface IReadOnlyList<'T>
interface IReadOnlyCollection<'T>
type List<'T> = class
interface IList<'T>
interface ICollection<'T>
interface IReadOnlyList<'T>
interface IReadOnlyCollection<'T>
interface seq<'T>
interface IList
interface ICollection
interface IEnumerable
[<System.Serializable>]
type List<'T> = class
interface IList<'T>
interface IList
interface IReadOnlyList<'T>
interface ICollection<'T>
interface seq<'T>
interface IEnumerable
interface ICollection
interface IReadOnlyCollection<'T>
Public Class List(Of T)
Implements ICollection(Of T), IEnumerable(Of T), IList, IList(Of T), IReadOnlyCollection(Of T), IReadOnlyList(Of T)
Public Class List(Of T)
Implements ICollection(Of T), IEnumerable(Of T), IList, IList(Of T)
형식 매개 변수
- T
목록에 있는 요소의 형식입니다.
- 상속
-
List<T>
- 파생
- 특성
- 구현
예제
다음 예제에서는 에 간단한 비즈니스 개체를 추가, 제거 및 삽입하는 List<T>방법을 보여 줍니다.
using System;
using System.Collections.Generic;
// Simple business object. A PartId is used to identify the type of part
// but the part name can change.
public class Part : IEquatable<Part>
{
public string PartName { get; set; }
public int PartId { get; set; }
public override string ToString()
{
return "ID: " + PartId + " Name: " + PartName;
}
public override bool Equals(object obj)
{
if (obj == null) return false;
Part objAsPart = obj as Part;
if (objAsPart == null) return false;
else return Equals(objAsPart);
}
public override int GetHashCode()
{
return PartId;
}
public bool Equals(Part other)
{
if (other == null) return false;
return (this.PartId.Equals(other.PartId));
}
// Should also override == and != operators.
}
public class Example
{
public static void Main()
{
// Create a list of parts.
List<Part> parts = new List<Part>();
// Add parts to the list.
parts.Add(new Part() { PartName = "crank arm", PartId = 1234 });
parts.Add(new Part() { PartName = "chain ring", PartId = 1334 });
parts.Add(new Part() { PartName = "regular seat", PartId = 1434 });
parts.Add(new Part() { PartName = "banana seat", PartId = 1444 });
parts.Add(new Part() { PartName = "cassette", PartId = 1534 });
parts.Add(new Part() { PartName = "shift lever", PartId = 1634 });
// Write out the parts in the list. This will call the overridden ToString method
// in the Part class.
Console.WriteLine();
foreach (Part aPart in parts)
{
Console.WriteLine(aPart);
}
// Check the list for part #1734. This calls the IEquatable.Equals method
// of the Part class, which checks the PartId for equality.
Console.WriteLine("\nContains(\"1734\"): {0}",
parts.Contains(new Part { PartId = 1734, PartName = "" }));
// Insert a new item at position 2.
Console.WriteLine("\nInsert(2, \"1834\")");
parts.Insert(2, new Part() { PartName = "brake lever", PartId = 1834 });
//Console.WriteLine();
foreach (Part aPart in parts)
{
Console.WriteLine(aPart);
}
Console.WriteLine("\nParts[3]: {0}", parts[3]);
Console.WriteLine("\nRemove(\"1534\")");
// This will remove part 1534 even though the PartName is different,
// because the Equals method only checks PartId for equality.
parts.Remove(new Part() { PartId = 1534, PartName = "cogs" });
Console.WriteLine();
foreach (Part aPart in parts)
{
Console.WriteLine(aPart);
}
Console.WriteLine("\nRemoveAt(3)");
// This will remove the part at index 3.
parts.RemoveAt(3);
Console.WriteLine();
foreach (Part aPart in parts)
{
Console.WriteLine(aPart);
}
/*
ID: 1234 Name: crank arm
ID: 1334 Name: chain ring
ID: 1434 Name: regular seat
ID: 1444 Name: banana seat
ID: 1534 Name: cassette
ID: 1634 Name: shift lever
Contains("1734"): False
Insert(2, "1834")
ID: 1234 Name: crank arm
ID: 1334 Name: chain ring
ID: 1834 Name: brake lever
ID: 1434 Name: regular seat
ID: 1444 Name: banana seat
ID: 1534 Name: cassette
ID: 1634 Name: shift lever
Parts[3]: ID: 1434 Name: regular seat
Remove("1534")
ID: 1234 Name: crank arm
ID: 1334 Name: chain ring
ID: 1834 Name: brake lever
ID: 1434 Name: regular seat
ID: 1444 Name: banana seat
ID: 1634 Name: shift lever
RemoveAt(3)
ID: 1234 Name: crank arm
ID: 1334 Name: chain ring
ID: 1834 Name: brake lever
ID: 1444 Name: banana seat
ID: 1634 Name: shift lever
*/
}
}
Imports System.Collections.Generic
' Simple business object. A PartId is used to identify the type of part
' but the part name can change.
Public Class Part
Implements IEquatable(Of Part)
Public Property PartName() As String
Get
Return m_PartName
End Get
Set(value As String)
m_PartName = Value
End Set
End Property
Private m_PartName As String
Public Property PartId() As Integer
Get
Return m_PartId
End Get
Set(value As Integer)
m_PartId = Value
End Set
End Property
Private m_PartId As Integer
Public Overrides Function ToString() As String
Return "ID: " & PartId & " Name: " & PartName
End Function
Public Overrides Function Equals(obj As Object) As Boolean
If obj Is Nothing Then
Return False
End If
Dim objAsPart As Part = TryCast(obj, Part)
If objAsPart Is Nothing Then
Return False
Else
Return Equals(objAsPart)
End If
End Function
Public Overrides Function GetHashCode() As Integer
Return PartId
End Function
Public Overloads Function Equals(other As Part) As Boolean _
Implements IEquatable(Of Part).Equals
If other Is Nothing Then
Return False
End If
Return (Me.PartId.Equals(other.PartId))
End Function
' Should also override == and != operators.
End Class
Public Class Example
Public Shared Sub Main()
' Create a list of parts.
Dim parts As New List(Of Part)()
' Add parts to the list.
parts.Add(New Part() With { _
.PartName = "crank arm", _
.PartId = 1234 _
})
parts.Add(New Part() With { _
.PartName = "chain ring", _
.PartId = 1334 _
})
parts.Add(New Part() With { _
.PartName = "regular seat", _
.PartId = 1434 _
})
parts.Add(New Part() With { _
.PartName = "banana seat", _
.PartId = 1444 _
})
parts.Add(New Part() With { _
.PartName = "cassette", _
.PartId = 1534 _
})
parts.Add(New Part() With { _
.PartName = "shift lever", _
.PartId = 1634 _
})
' Write out the parts in the list. This will call the overridden ToString method
' in the Part class.
Console.WriteLine()
For Each aPart As Part In parts
Console.WriteLine(aPart)
Next
' Check the list for part #1734. This calls the IEquatable.Equals method
' of the Part class, which checks the PartId for equality.
Console.WriteLine(vbLf & "Contains(""1734""): {0}", parts.Contains(New Part() With { _
.PartId = 1734, _
.PartName = "" _
}))
' Insert a new item at position 2.
Console.WriteLine(vbLf & "Insert(2, ""1834"")")
parts.Insert(2, New Part() With { _
.PartName = "brake lever", _
.PartId = 1834 _
})
'Console.WriteLine();
For Each aPart As Part In parts
Console.WriteLine(aPart)
Next
Console.WriteLine(vbLf & "Parts[3]: {0}", parts(3))
Console.WriteLine(vbLf & "Remove(""1534"")")
' This will remove part 1534 even though the PartName is different,
' because the Equals method only checks PartId for equality.
parts.Remove(New Part() With { _
.PartId = 1534, _
.PartName = "cogs" _
})
Console.WriteLine()
For Each aPart As Part In parts
Console.WriteLine(aPart)
Next
Console.WriteLine(vbLf & "RemoveAt(3)")
' This will remove part at index 3.
parts.RemoveAt(3)
Console.WriteLine()
For Each aPart As Part In parts
Console.WriteLine(aPart)
Next
End Sub
'
' This example code produces the following output:
' ID: 1234 Name: crank arm
' ID: 1334 Name: chain ring
' ID: 1434 Name: regular seat
' ID: 1444 Name: banana seat
' ID: 1534 Name: cassette
' ID: 1634 Name: shift lever
'
' Contains("1734"): False
'
' Insert(2, "1834")
' ID: 1234 Name: crank arm
' ID: 1334 Name: chain ring
' ID: 1834 Name: brake lever
' ID: 1434 Name: regular seat
' ID: 1444 Name: banana seat
' ID: 1534 Name: cassette
' ID: 1634 Name: shift lever
'
' Parts[3]: ID: 1434 Name: regular seat
'
' Remove("1534")
'
' ID: 1234 Name: crank arm
' ID: 1334 Name: chain ring
' ID: 1834 Name: brake lever
' ID: 1434 Name: regular seat
' ID: 1444 Name: banana seat
' ID: 1634 Name: shift lever
' '
' RemoveAt(3)
'
' ID: 1234 Name: crank arm
' ID: 1334 Name: chain ring
' ID: 1834 Name: brake lever
' ID: 1444 Name: banana seat
' ID: 1634 Name: shift lever
'
End Class
// Simple business object. A PartId is used to identify the type of part
// but the part name can change.
[<CustomEquality; NoComparison>]
type Part = { PartId : int ; mutable PartName : string } with
override this.GetHashCode() = hash this.PartId
override this.Equals(other) =
match other with
| :? Part as p -> this.PartId = p.PartId
| _ -> false
override this.ToString() = sprintf "ID: %i Name: %s" this.PartId this.PartName
[<EntryPoint>]
let main argv =
// We refer to System.Collections.Generic.List<'T> by its type
// abbreviation ResizeArray<'T> to avoid conflicts with the F# List module.
// Note: In F# code, F# linked lists are usually preferred over
// ResizeArray<'T> when an extendable collection is required.
let parts = ResizeArray<_>()
parts.Add({PartName = "crank arm" ; PartId = 1234})
parts.Add({PartName = "chain ring"; PartId = 1334 })
parts.Add({PartName = "regular seat"; PartId = 1434 })
parts.Add({PartName = "banana seat"; PartId = 1444 })
parts.Add({PartName = "cassette"; PartId = 1534 })
parts.Add({PartName = "shift lever"; PartId = 1634 })
// Write out the parts in the ResizeArray. This will call the overridden ToString method
// in the Part type
printfn ""
parts |> Seq.iter (fun p -> printfn "%O" p)
// Check the ResizeArray for part #1734. This calls the IEquatable.Equals method
// of the Part type, which checks the PartId for equality.
printfn "\nContains(\"1734\"): %b" (parts.Contains({PartId=1734; PartName=""}))
// Insert a new item at position 2.
printfn "\nInsert(2, \"1834\")"
parts.Insert(2, { PartName = "brake lever"; PartId = 1834 })
// Write out all parts
parts |> Seq.iter (fun p -> printfn "%O" p)
printfn "\nParts[3]: %O" parts.[3]
printfn "\nRemove(\"1534\")"
// This will remove part 1534 even though the PartName is different,
// because the Equals method only checks PartId for equality.
// Since Remove returns true or false, we need to ignore the result
parts.Remove({PartId=1534; PartName="cogs"}) |> ignore
// Write out all parts
printfn ""
parts |> Seq.iter (fun p -> printfn "%O" p)
printfn "\nRemoveAt(3)"
// This will remove the part at index 3.
parts.RemoveAt(3)
// Write out all parts
printfn ""
parts |> Seq.iter (fun p -> printfn "%O" p)
0 // return an integer exit code
다음 예제에서는 문자열 형식의 제네릭 클래스의 List<T> 여러 속성과 메서드를 보여 줍니다. (복합 형식의 예제는 List<T> 메서드를 Contains 참조하세요.)
매개 변수가 없는 생성자는 기본 용량을 사용하여 문자열 목록을 만드는 데 사용됩니다. Capacity 속성이 표시되고 메서드를 Add 사용하여 여러 항목을 추가합니다. 항목이 나열되고 Capacity 속성이 속성과 Count 함께 다시 표시되어 필요에 따라 용량이 증가했음을 표시합니다.
메서드는 Contains 목록에 항목이 있는지 테스트하는 데 사용되며, Insert 메서드는 목록 중간에 새 항목을 삽입하는 데 사용되며 목록의 내용이 다시 표시됩니다.
기본 Item[] 속성(C#의 인덱서)은 항목을 검색하는 데 사용되며, Remove 메서드는 이전에 추가된 중복 항목의 첫 번째 instance 제거하는 데 사용되며 콘텐츠가 다시 표시됩니다. 메서드는 Remove 발생한 첫 번째 instance 항상 제거합니다.
메서드는 TrimExcess 개수와 일치하는 용량을 줄이는 데 사용되며 및 CapacityCount 속성이 표시됩니다. 사용하지 않는 용량이 총 용량의 10% 미만이었다면 목록의 크기가 조정되지 않았을 것입니다.
마지막으로 메서드는 Clear 목록에서 모든 항목을 제거하는 데 사용되며 Capacity 및 Count 속성이 표시됩니다.
using namespace System;
using namespace System::Collections::Generic;
void main()
{
List<String^>^ dinosaurs = gcnew List<String^>();
Console::WriteLine("\nCapacity: {0}", dinosaurs->Capacity);
dinosaurs->Add("Tyrannosaurus");
dinosaurs->Add("Amargasaurus");
dinosaurs->Add("Mamenchisaurus");
dinosaurs->Add("Deinonychus");
dinosaurs->Add("Compsognathus");
Console::WriteLine();
for each(String^ dinosaur in dinosaurs )
{
Console::WriteLine(dinosaur);
}
Console::WriteLine("\nCapacity: {0}", dinosaurs->Capacity);
Console::WriteLine("Count: {0}", dinosaurs->Count);
Console::WriteLine("\nContains(\"Deinonychus\"): {0}",
dinosaurs->Contains("Deinonychus"));
Console::WriteLine("\nInsert(2, \"Compsognathus\")");
dinosaurs->Insert(2, "Compsognathus");
Console::WriteLine();
for each(String^ dinosaur in dinosaurs )
{
Console::WriteLine(dinosaur);
}
Console::WriteLine("\ndinosaurs[3]: {0}", dinosaurs[3]);
Console::WriteLine("\nRemove(\"Compsognathus\")");
dinosaurs->Remove("Compsognathus");
Console::WriteLine();
for each(String^ dinosaur in dinosaurs )
{
Console::WriteLine(dinosaur);
}
dinosaurs->TrimExcess();
Console::WriteLine("\nTrimExcess()");
Console::WriteLine("Capacity: {0}", dinosaurs->Capacity);
Console::WriteLine("Count: {0}", dinosaurs->Count);
dinosaurs->Clear();
Console::WriteLine("\nClear()");
Console::WriteLine("Capacity: {0}", dinosaurs->Capacity);
Console::WriteLine("Count: {0}", dinosaurs->Count);
}
/* This code example produces the following output:
Capacity: 0
Tyrannosaurus
Amargasaurus
Mamenchisaurus
Deinonychus
Compsognathus
Capacity: 8
Count: 5
Contains("Deinonychus"): True
Insert(2, "Compsognathus")
Tyrannosaurus
Amargasaurus
Compsognathus
Mamenchisaurus
Deinonychus
Compsognathus
dinosaurs[3]: Mamenchisaurus
Remove("Compsognathus")
Tyrannosaurus
Amargasaurus
Mamenchisaurus
Deinonychus
Compsognathus
TrimExcess()
Capacity: 5
Count: 5
Clear()
Capacity: 5
Count: 0
*/
List<string> dinosaurs = new List<string>();
Console.WriteLine("\nCapacity: {0}", dinosaurs.Capacity);
dinosaurs.Add("Tyrannosaurus");
dinosaurs.Add("Amargasaurus");
dinosaurs.Add("Mamenchisaurus");
dinosaurs.Add("Deinonychus");
dinosaurs.Add("Compsognathus");
Console.WriteLine();
foreach(string dinosaur in dinosaurs)
{
Console.WriteLine(dinosaur);
}
Console.WriteLine("\nCapacity: {0}", dinosaurs.Capacity);
Console.WriteLine("Count: {0}", dinosaurs.Count);
Console.WriteLine("\nContains(\"Deinonychus\"): {0}",
dinosaurs.Contains("Deinonychus"));
Console.WriteLine("\nInsert(2, \"Compsognathus\")");
dinosaurs.Insert(2, "Compsognathus");
Console.WriteLine();
foreach(string dinosaur in dinosaurs)
{
Console.WriteLine(dinosaur);
}
// Shows accessing the list using the Item property.
Console.WriteLine("\ndinosaurs[3]: {0}", dinosaurs[3]);
Console.WriteLine("\nRemove(\"Compsognathus\")");
dinosaurs.Remove("Compsognathus");
Console.WriteLine();
foreach(string dinosaur in dinosaurs)
{
Console.WriteLine(dinosaur);
}
dinosaurs.TrimExcess();
Console.WriteLine("\nTrimExcess()");
Console.WriteLine("Capacity: {0}", dinosaurs.Capacity);
Console.WriteLine("Count: {0}", dinosaurs.Count);
dinosaurs.Clear();
Console.WriteLine("\nClear()");
Console.WriteLine("Capacity: {0}", dinosaurs.Capacity);
Console.WriteLine("Count: {0}", dinosaurs.Count);
/* This code example produces the following output:
Capacity: 0
Tyrannosaurus
Amargasaurus
Mamenchisaurus
Deinonychus
Compsognathus
Capacity: 8
Count: 5
Contains("Deinonychus"): True
Insert(2, "Compsognathus")
Tyrannosaurus
Amargasaurus
Compsognathus
Mamenchisaurus
Deinonychus
Compsognathus
dinosaurs[3]: Mamenchisaurus
Remove("Compsognathus")
Tyrannosaurus
Amargasaurus
Mamenchisaurus
Deinonychus
Compsognathus
TrimExcess()
Capacity: 5
Count: 5
Clear()
Capacity: 5
Count: 0
*/
Imports System.Collections.Generic
Public Class Example
Public Shared Sub Main()
Dim dinosaurs As New List(Of String)
Console.WriteLine(vbLf & "Capacity: {0}", dinosaurs.Capacity)
dinosaurs.Add("Tyrannosaurus")
dinosaurs.Add("Amargasaurus")
dinosaurs.Add("Mamenchisaurus")
dinosaurs.Add("Deinonychus")
dinosaurs.Add("Compsognathus")
Console.WriteLine()
For Each dinosaur As String In dinosaurs
Console.WriteLine(dinosaur)
Next
Console.WriteLine(vbLf & "Capacity: {0}", dinosaurs.Capacity)
Console.WriteLine("Count: {0}", dinosaurs.Count)
Console.WriteLine(vbLf & "Contains(""Deinonychus""): {0}", _
dinosaurs.Contains("Deinonychus"))
Console.WriteLine(vbLf & "Insert(2, ""Compsognathus"")")
dinosaurs.Insert(2, "Compsognathus")
Console.WriteLine()
For Each dinosaur As String In dinosaurs
Console.WriteLine(dinosaur)
Next
' Shows how to access the list using the Item property.
Console.WriteLine(vbLf & "dinosaurs(3): {0}", dinosaurs(3))
Console.WriteLine(vbLf & "Remove(""Compsognathus"")")
dinosaurs.Remove("Compsognathus")
Console.WriteLine()
For Each dinosaur As String In dinosaurs
Console.WriteLine(dinosaur)
Next
dinosaurs.TrimExcess()
Console.WriteLine(vbLf & "TrimExcess()")
Console.WriteLine("Capacity: {0}", dinosaurs.Capacity)
Console.WriteLine("Count: {0}", dinosaurs.Count)
dinosaurs.Clear()
Console.WriteLine(vbLf & "Clear()")
Console.WriteLine("Capacity: {0}", dinosaurs.Capacity)
Console.WriteLine("Count: {0}", dinosaurs.Count)
End Sub
End Class
' This code example produces the following output:
'
'Capacity: 0
'
'Tyrannosaurus
'Amargasaurus
'Mamenchisaurus
'Deinonychus
'Compsognathus
'
'Capacity: 8
'Count: 5
'
'Contains("Deinonychus"): True
'
'Insert(2, "Compsognathus")
'
'Tyrannosaurus
'Amargasaurus
'Compsognathus
'Mamenchisaurus
'Deinonychus
'Compsognathus
'
'dinosaurs(3): Mamenchisaurus
'
'Remove("Compsognathus")
'
'Tyrannosaurus
'Amargasaurus
'Mamenchisaurus
'Deinonychus
'Compsognathus
'
'TrimExcess()
'Capacity: 5
'Count: 5
'
'Clear()
'Capacity: 5
'Count: 0
[<EntryPoint>]
let main argv =
// We refer to System.Collections.Generic.List<'T> by its type
// abbreviation ResizeArray<'T> to avoid conflict with the List module.
// Note: In F# code, F# linked lists are usually preferred over
// ResizeArray<'T> when an extendable collection is required.
let dinosaurs = ResizeArray<_>()
// Write out the dinosaurs in the ResizeArray.
let printDinosaurs() =
printfn ""
dinosaurs |> Seq.iter (fun p -> printfn "%O" p)
printfn "\nCapacity: %i" dinosaurs.Capacity
dinosaurs.Add("Tyrannosaurus")
dinosaurs.Add("Amargasaurus")
dinosaurs.Add("Mamenchisaurus")
dinosaurs.Add("Deinonychus")
dinosaurs.Add("Compsognathus")
printDinosaurs()
printfn "\nCapacity: %i" dinosaurs.Capacity
printfn "Count: %i" dinosaurs.Count
printfn "\nContains(\"Deinonychus\"): %b" (dinosaurs.Contains("Deinonychus"))
printfn "\nInsert(2, \"Compsognathus\")"
dinosaurs.Insert(2, "Compsognathus")
printDinosaurs()
// Shows accessing the list using the Item property.
printfn "\ndinosaurs[3]: %s" dinosaurs.[3]
printfn "\nRemove(\"Compsognathus\")"
dinosaurs.Remove("Compsognathus") |> ignore
printDinosaurs()
dinosaurs.TrimExcess()
printfn "\nTrimExcess()"
printfn "Capacity: %i" dinosaurs.Capacity
printfn "Count: %i" dinosaurs.Count
dinosaurs.Clear()
printfn "\nClear()"
printfn "Capacity: %i" dinosaurs.Capacity
printfn "Count: %i" dinosaurs.Count
0 // return an integer exit code
(* This code example produces the following output:
Capacity: 0
Tyrannosaurus
Amargasaurus
Mamenchisaurus
Deinonychus
Compsognathus
Capacity: 8
Count: 5
Contains("Deinonychus"): true
Insert(2, "Compsognathus")
Tyrannosaurus
Amargasaurus
Compsognathus
Mamenchisaurus
Deinonychus
Compsognathus
dinosaurs[3]: Mamenchisaurus
Remove("Compsognathus")
Tyrannosaurus
Amargasaurus
Mamenchisaurus
Deinonychus
Compsognathus
TrimExcess()
Capacity: 5
Count: 5
Clear()
Capacity: 5
Count: 0
*)
설명
클래스는 List<T> 클래스에 해당하는 제네릭입니다 ArrayList . 필요에 따라 크기가 IList<T> 동적으로 증가하는 배열을 사용하여 제네릭 인터페이스를 구현합니다.
또는 AddRange 메서드를 List<T> 사용하여 Add 에 항목을 추가할 수 있습니다.
클래스는 List<T> 같음 비교자와 순서 비교자를 모두 사용합니다.
, , IndexOfLastIndexOf및 Remove 와 같은 Contains메서드는 목록 요소에 대해 같음 비교자를 사용합니다. 형식
T
의 기본 같음 비교자는 다음과 같이 결정됩니다. 형식T
이 제네릭 인터페이스를 IEquatable<T> 구현하는 경우 같음 비교자는 해당 인터페이스의 메서드이고 Equals(T) , 그렇지 않으면 기본 같음 비교자는 입니다 Object.Equals(Object).및 Sort 와 같은 BinarySearch 메서드는 목록 요소에 대해 순서 비교자를 사용합니다. 형식
T
의 기본 비교자는 다음과 같이 결정됩니다. 형식T
이 제네릭 인터페이스를 IComparable<T> 구현하는 경우 기본 비교자는 해당 인터페이스의 메서드이고 CompareTo(T) , 그렇지 않으면 typeT
이 비일반 IComparable 인터페이스를 구현하는 경우 기본 비교자는 해당 인터페이스의 메서드입니다 CompareTo(Object) . 형식T
이 두 인터페이스를 모두 구현하지 않으면 기본 비교자가 없으며 비교자 또는 비교 대리자를 명시적으로 제공해야 합니다.
는 List<T> 정렬되도록 보장되지 않습니다. 를 정렬해야 하는 작업(예: BinarySearch)을 List<T> 수행하기 전에 를 정렬 List<T> 해야 합니다.
이 컬렉션의 요소는 정수 인덱스로 액세스할 수 있습니다. 이 컬렉션의 인덱스는 0부터 시작 합니다.
.NET Framework 전용: 매우 큰 List<T> 개체의 경우 런타임 환경에서 구성 요소의 <gcAllowVeryLargeObjects>
특성을 로 설정 enabled
하여 64비트 시스템에서 최대 용량을 20억 요소로 true
늘릴 수 있습니다.
List<T> 는 null
참조 형식에 유효한 값으로 허용되고 중복 요소를 허용합니다.
변경할 수 없는 버전의 클래스는 를 List<T> 참조하세요 ImmutableList<T>.
성능 고려 사항
둘 다 비슷한 기능을 List<T> 가진 또는 ArrayList 클래스를 List<T> 사용할지 여부를 결정할 때 클래스는 대부분의 경우 더 잘 수행되며 형식이 안전합니다. 참조 형식이 클래스 형식 List<T> 에 T
사용되는 경우 두 클래스의 동작은 동일합니다. 그러나 값 형식이 형식 T
에 사용되는 경우 구현 및 boxing 문제를 고려해야 합니다.
값 형식이 형식 T
에 사용되는 경우 컴파일러는 해당 값 형식에 List<T> 대한 클래스의 구현을 생성합니다. 즉, 요소를 사용할 수 있기 전에 개체의 List<T> 목록 요소를 boxed할 필요가 없으며, 약 500개 목록 요소를 만든 후에는 boxing list 요소가 아닌 에 의해 저장된 메모리가 클래스 구현을 생성하는 데 사용되는 메모리보다 큽습니다.
형식 T
에 사용되는 값 형식이 제네릭 인터페이스를 구현해야 합니다 IEquatable<T> . 그렇지 않은 경우 와 같은 Contains 메서드는 Object.Equals(Object) 영향을 받는 list 요소의 상자를 지정하는 메서드를 호출해야 합니다. 값 형식이 인터페이스를 IComparable 구현하고 소스 코드를 소유하는 경우 및 메서드가 IComparable<T> boxing 목록 요소에서 발생하지 않도록 BinarySearchSort 제네릭 인터페이스도 구현합니다. 소스 코드를 소유하지 않은 경우 및 Sort 메서드에 개체를 BinarySearch 전달 IComparer<T> 합니다.
클래스를 사용하거나 강력한 형식의 래퍼 컬렉션을 직접 작성하는 대신 클래스의 List<T> 형식별 구현을 사용하는 ArrayList 것이 좋습니다. 이는 구현이 .NET Framework 이미 수행하는 작업을 수행해야 하고 공용 언어 런타임이 구현에서 수행할 수 없는 Microsoft 중간 언어 코드 및 메타데이터를 공유할 수 있기 때문입니다.
F# 고려 사항
클래스는 List<T> F# 코드에서 자주 사용되지 않습니다. 대신 변경할 수 없는, Singly-linked 목록인 목록이 일반적으로 선호됩니다. F# List
은 순서가 지정되고 변경할 수 없는 일련의 값을 제공하며 기능 스타일 개발에 사용할 수 있도록 지원됩니다. F# List<T> 에서 사용하는 경우 클래스는 일반적으로 F# 목록과의 명명 충돌을 방지하기 위해 형식 약어로 참조 ResizeArray<'T>
됩니다.
생성자
List<T>() |
비어 있는 상태에서 기본 초기 용량을 가지는 List<T> 클래스의 새 인스턴스를 초기화합니다. |
List<T>(IEnumerable<T>) |
지정된 컬렉션에서 복사한 요소를 포함하고 복사한 요소를 모두 수용할 수 있을 정도의 용량을 가진 List<T> 클래스의 새 인스턴스를 초기화합니다. |
List<T>(Int32) |
비어 있는 상태에서 지정한 초기 용량을 가지는 List<T> 클래스의 새 인스턴스를 초기화합니다. |
속성
Capacity |
크기를 조정하지 않고 내부 데이터 구조가 보유할 수 있는 전체 요소 수를 가져오거나 설정합니다. |
Count |
List<T>에 포함된 요소 수를 가져옵니다. |
Item[Int32] |
지정한 인덱스에 있는 요소를 가져오거나 설정합니다. |
메서드
Add(T) |
개체를 List<T>의 끝 부분에 추가합니다. |
AddRange(IEnumerable<T>) |
지정된 컬렉션의 요소를 List<T>의 끝에 추가합니다. |
AsReadOnly() |
현재 컬렉션에 대한 읽기 전용 ReadOnlyCollection<T> 래퍼를 반환합니다. |
BinarySearch(Int32, Int32, T, IComparer<T>) |
지정된 비교자를 사용하여 정렬된 List<T>의 요소 범위에서 요소를 검색하고 요소의 인덱스(0부터 시작)를 반환합니다. |
BinarySearch(T) |
기본 비교자를 사용하여 정렬된 전체 List<T>에서 요소를 검색하고 요소의 인덱스(0부터 시작)를 반환합니다. |
BinarySearch(T, IComparer<T>) |
지정된 비교자를 사용하여 정렬된 전체 List<T>에서 요소를 검색하고 요소의 인덱스(0부터 시작)를 반환합니다. |
Clear() |
List<T>에서 요소를 모두 제거합니다. |
Contains(T) |
List<T>에 요소가 있는지 여부를 확인합니다. |
ConvertAll<TOutput>(Converter<T,TOutput>) |
현재 List<T>의 요소를 다른 형식으로 변환하고 변환된 요소를 포함하는 목록을 반환합니다. |
CopyTo(Int32, T[], Int32, Int32) |
대상 배열의 지정된 인덱스에서 시작하여 List<T>에 있는 일련의 요소를 호환되는 1차원 배열에 복사합니다. |
CopyTo(T[]) |
대상 배열의 처음부터 시작하여 전체 List<T>을 호환되는 1차원 배열에 복사합니다. |
CopyTo(T[], Int32) |
대상 배열의 지정된 인덱스에서 시작하여 전체 List<T>을 호환되는 1차원 배열에 복사합니다. |
EnsureCapacity(Int32) |
이 목록의 용량이 지정된 |
Equals(Object) |
지정된 개체가 현재 개체와 같은지 확인합니다. (다음에서 상속됨 Object) |
Exists(Predicate<T>) |
지정된 조건자에 정의된 조건과 일치하는 요소가 List<T>에 포함되어 있는지 여부를 확인합니다. |
Find(Predicate<T>) |
지정된 조건자에 정의된 조건과 일치하는 요소를 검색하고 전체 List<T>에서 처음으로 검색한 요소를 반환합니다. |
FindAll(Predicate<T>) |
지정한 조건자에 정의된 조건과 일치하는 모든 요소를 검색합니다. |
FindIndex(Int32, Int32, Predicate<T>) |
지정된 조건자에 정의된 조건과 일치하는 요소를 검색하고 지정된 인덱스부터 시작하여 지정된 수의 요소를 포함하는 List<T>의 요소 범위에서 일치하는 요소 중 첫 번째 요소의 인덱스(0부터 시작)를 반환합니다. |
FindIndex(Int32, Predicate<T>) |
지정된 조건자에 정의된 조건과 일치하는 요소를 검색하여 지정된 인덱스에서 마지막 요소로 확장하는 List<T>의 요소 범위에서 일치하는 요소 중 첫 번째 요소의 인덱스(0부터 시작)를 반환합니다. |
FindIndex(Predicate<T>) |
지정된 조건자에 정의된 조건과 일치하는 요소를 검색하여 전체 List<T>에서 일치하는 요소 중 첫 번째 요소의 인덱스(0부터 시작)를 반환합니다. |
FindLast(Predicate<T>) |
지정된 조건자에 정의된 조건과 일치하는 요소를 검색하고 전체 List<T>에서 마지막으로 검색한 요소를 반환합니다. |
FindLastIndex(Int32, Int32, Predicate<T>) |
지정된 조건자에 정의된 조건과 일치하는 요소를 검색하여 지정된 수의 요소가 들어 있고 지정된 인덱스에서 끝나는 List<T> 의 요소 범위에서 일치하는 요소 중 마지막 요소의 인덱스(0부터 시작)를 반환합니다. |
FindLastIndex(Int32, Predicate<T>) |
지정된 조건자에 정의된 조건과 일치하는 요소를 검색하여 첫 번째 요소에서 지정된 인덱스로 확장하는 List<T>의 요소 범위에서 일치하는 요소 중 마지막 요소의 인덱스(0부터 시작)를 반환합니다. |
FindLastIndex(Predicate<T>) |
지정된 조건자에 정의된 조건과 일치하는 요소를 검색하여 전체 List<T>에서 일치하는 요소 중 마지막 요소의 인덱스(0부터 시작)를 반환합니다. |
ForEach(Action<T>) |
List<T>의 각 요소에 대해 지정된 작업을 수행합니다. |
GetEnumerator() |
List<T>를 반복하는 열거자를 반환합니다. |
GetHashCode() |
기본 해시 함수로 작동합니다. (다음에서 상속됨 Object) |
GetRange(Int32, Int32) |
소스 List<T>에 있는 일련의 요소에 대한 단순 복사본을 만듭니다. |
GetType() |
현재 인스턴스의 Type을 가져옵니다. (다음에서 상속됨 Object) |
IndexOf(T) |
지정된 개체를 검색하고, 전체 List<T>에서 처음으로 검색한 개체의 인덱스(0부터 시작)를 반환합니다. |
IndexOf(T, Int32) |
지정된 개체를 검색하고, 지정된 인덱스부터 마지막 요소까지 포함하는 List<T>의 요소 범위에서 처음으로 검색한 개체의 인덱스(0부터 시작)를 반환합니다. |
IndexOf(T, Int32, Int32) |
지정된 개체를 검색하고, 지정된 인덱스에서 시작하여 지정된 수의 요소를 포함하는 List<T>의 요소 범위에서 처음으로 검색한 개체의 인덱스(0부터 시작)를 반환합니다. |
Insert(Int32, T) |
List<T>의 지정된 인덱스에 요소를 삽입합니다. |
InsertRange(Int32, IEnumerable<T>) |
List<T>의 지정된 인덱스에 컬렉션의 요소를 삽입합니다. |
LastIndexOf(T) |
지정된 개체를 검색하고, 전체 List<T>에서 마지막으로 검색한 개체의 인덱스(0부터 시작)를 반환합니다. |
LastIndexOf(T, Int32) |
지정된 개체를 검색하고, 첫 번째 요소부터 지정된 인덱스까지 포함하는 List<T>의 요소 범위에서 마지막으로 검색한 개체의 인덱스(0부터 시작)를 반환합니다. |
LastIndexOf(T, Int32, Int32) |
지정된 개체를 검색하며, 지정된 수의 요소를 포함하고 지정된 인덱스에서 끝나는 List<T>의 요소 범위에서 마지막으로 검색한 개체의 인덱스(0부터 시작)를 반환합니다. |
MemberwiseClone() |
현재 Object의 단순 복사본을 만듭니다. (다음에서 상속됨 Object) |
Remove(T) |
List<T>에서 맨 처음 발견되는 특정 개체를 제거합니다. |
RemoveAll(Predicate<T>) |
지정된 조건자에 정의된 조건과 일치하는 요소를 모두 제거합니다. |
RemoveAt(Int32) |
List<T>의 지정된 인덱스에 있는 요소를 제거합니다. |
RemoveRange(Int32, Int32) |
List<T>에서 요소의 범위를 제거합니다. |
Reverse() |
전체 List<T>에서 요소의 순서를 반대로 바꿉니다. |
Reverse(Int32, Int32) |
지정된 범위에서 요소의 순서를 반대로 바꿉니다. |
Slice(Int32, Int32) |
소스 List<T>에 있는 일련의 요소에 대한 단순 복사본을 만듭니다. |
Sort() |
기본 비교자를 사용하여 전체 List<T>의 요소를 정렬합니다. |
Sort(Comparison<T>) |
지정된 Comparison<T>을 사용하여 전체 List<T>의 요소를 정렬합니다. |
Sort(IComparer<T>) |
지정된 비교자를 사용하여 전체 List<T>에 있는 요소를 정렬합니다. |
Sort(Int32, Int32, IComparer<T>) |
지정된 비교자를 사용하여 List<T>의 요소 범위에 있는 요소를 정렬합니다. |
ToArray() |
List<T>의 요소를 새 배열에 복사합니다. |
ToString() |
현재 개체를 나타내는 문자열을 반환합니다. (다음에서 상속됨 Object) |
TrimExcess() |
List<T>에 있는 요소의 실제 수가 임계값보다 작은 경우 용량을 요소 수로 설정합니다. |
TrueForAll(Predicate<T>) |
List<T>의 모든 요소가 지정된 조건자에 정의된 조건과 일치하는지 여부를 확인합니다. |
명시적 인터페이스 구현
ICollection.CopyTo(Array, Int32) |
특정 ICollection 인덱스부터 시작하여 Array의 요소를 Array에 복사합니다. |
ICollection.IsSynchronized |
ICollection에 대한 액세스가 동기화되어 스레드로부터 안전하게 보호되는지를 나타내는 값을 가져옵니다. |
ICollection.SyncRoot |
ICollection에 대한 액세스를 동기화하는 데 사용할 수 있는 개체를 가져옵니다. |
ICollection<T>.IsReadOnly |
ICollection<T>가 읽기 전용인지 여부를 나타내는 값을 가져옵니다. |
IEnumerable.GetEnumerator() |
컬렉션을 반복하는 열거자를 반환합니다. |
IEnumerable<T>.GetEnumerator() |
컬렉션을 반복하는 열거자를 반환합니다. |
IList.Add(Object) |
IList에 항목을 추가합니다. |
IList.Contains(Object) |
IList에 특정 값이 들어 있는지 여부를 확인합니다. |
IList.IndexOf(Object) |
IList에서 특정 항목의 인덱스를 결정합니다. |
IList.Insert(Int32, Object) |
항목을 IList의 지정된 인덱스에 삽입합니다. |
IList.IsFixedSize |
IList의 크기가 고정되어 있는지 여부를 나타내는 값을 가져옵니다. |
IList.IsReadOnly |
IList가 읽기 전용인지 여부를 나타내는 값을 가져옵니다. |
IList.Item[Int32] |
지정한 인덱스에 있는 요소를 가져오거나 설정합니다. |
IList.Remove(Object) |
IList에서 맨 처음 발견되는 특정 개체를 제거합니다. |
확장 메서드
적용 대상
스레드 보안
공용 정적 (Shared
Visual Basic의)이 형식의 멤버는 스레드로부터 안전 합니다. 인스턴스 구성원은 스레드로부터의 안전성이 보장되지 않습니다.
에서 여러 읽기 작업을 List<T>수행하는 것이 안전하지만 컬렉션이 읽는 동안 수정되는 경우 문제가 발생할 수 있습니다. 스레드 안전을 보장하려면 읽기 또는 쓰기 작업 중에 컬렉션을 잠급니다. 읽기 및 쓰기를 위해 여러 스레드에서 컬렉션에 액세스할 수 있도록 하려면 고유한 동기화를 구현해야 합니다. 기본 제공 동기화가 있는 컬렉션은 네임스페이스의 클래스를 System.Collections.Concurrent 참조하세요. 기본적으로 스레드로부터 안전한 대안은 클래스를 ImmutableList<T> 참조하세요.
추가 정보
피드백
다음에 대한 사용자 의견 제출 및 보기