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
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
*/
}
}
' 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[Int32] 속성(C#의 인덱서)은 항목을 검색하는 데 사용되고, Remove 메서드는 이전에 추가된 중복 항목의 첫 번째 인스턴스를 제거하는 데 사용되며, 내용이 다시 표시됩니다. 메서드는 Remove 항상 발생한 첫 번째 인스턴스를 제거합니다.
이 TrimExcess 메서드는 개수와 일치하는 용량을 줄이는 데 사용되며 Capacity 속성과 Count 속성이 표시됩니다. 사용하지 않는 용량이 총 용량의 10% 미만이면 목록의 크기가 조정되지 않았을 것입니다.
마지막으로 이 Clear 메서드는 목록에서 모든 항목을 제거하는 데 사용되며 Capacity 속성과 Count 속성이 표시됩니다.
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
*/
Public Class Example2
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> 동적으로 증가하는 배열을 사용하여 제네릭 인터페이스를 구현합니다.
List<T>에 항목을 추가하려면 Add 또는 AddRange 메서드를 사용할 수 있습니다.
클래스는 List<T> 같음 비교자와 순서 비교자를 모두 사용합니다.
Contains, IndexOf, LastIndexOf, 및 Remove와 같은 메서드는 목록 요소에 대해 같음 비교자를 사용합니다. 형식
T의 기본 같음 비교자는 다음과 같이 결정됩니다. 형식T이 제네릭 인터페이스 IEquatable<T>를 구현하는 경우, 같음 비교자는 그 인터페이스의 메서드 Equals(T)이고, 그렇지 않으면 기본 같음 비교자는 Object.Equals(Object)입니다.BinarySearch 및 Sort와 같은 메서드는 목록 요소에 대한 순서 비교자를 사용합니다. 형식
T에 대한 기본 비교자는 다음과 같이 결정됩니다. 형식T이 제네릭 인터페이스를 구현하는 경우 기본 비교자는 해당 인터페이스의 메서드이고IComparable<T>, 그렇지 않으면 형식 CompareTo(T) 이 비제너릭T인터페이스를 구현하는 경우 기본 비교자는 해당 인터페이스의 메서드입니다 IComparableCompareTo(Object). 형식T이 두 인터페이스를 모두 구현하지 않는 경우 기본 비교자가 없으며 비교자 또는 비교 대리자를 명시적으로 제공해야 합니다.
List<T> 정렬이 보장되지 않습니다. List<T>을(를) 정렬한 후 BinarySearch이(가) 정렬되어야 하는 연산(예: List<T>)을 수행해야 합니다.
이 컬렉션의 요소는 정수 인덱스로 액세스할 수 있습니다. 이 컬렉션의 인덱스는 0부터 시작합니다.
List<T> 는 null 참조 형식에 유효한 값으로 허용되며 중복 요소를 허용합니다.
변경할 수 없는 List<T> 클래스 버전에 대해서는 ImmutableList<T>를 참조하세요.
성능 고려 사항
두 가지 유사한 기능을 가진 List<T> 클래스와 ArrayList 클래스 중에서 어떤 것을 사용할지 결정할 때, 대부분의 경우 List<T> 클래스가 더 성능이 뛰어나고 형식 안전하다는 점을 기억하십시오. 클래스의 형식으로 T 참조 형식을 List<T> 사용하는 경우, 해당 두 클래스의 동작은 동일합니다. 그러나 값 형식이 형식 T에 사용되는 경우 구현 및 박싱 문제를 고려해야 합니다.
값 형식이 형식 T에 사용되는 경우 컴파일러는 해당 값 형식에 List<T> 대한 클래스의 구현을 생성합니다. 즉, 요소를 사용하기 전에 List<T> 객체의 목록 요소를 박싱할 필요가 없으며, 약 500개의 목록 요소를 만든 후에는 박싱하지 않은 목록 요소로 인해 저장된 메모리가 클래스 구현을 생성하는 데 사용되는 메모리보다 더 커집니다.
형식 T에 사용되는 값 형식이 제네릭 인터페이스를 IEquatable<T> 구현하는지 확인하십시오. 그렇지 않은 경우와 같은 Contains 메서드는 영향을 받는 목록 요소의 Object.Equals(Object) 상자를 지정하는 메서드를 호출해야 합니다. 값 형식이 IComparable 인터페이스를 구현하고 소스 코드를 소유하는 경우, IComparable<T> 제네릭 인터페이스도 구현하여 BinarySearch 및 Sort 메서드가 목록 요소를 박싱하지 않도록 합니다. 소스 코드를 소유하지 않은 경우 IComparer<T> 객체를 BinarySearch 및 Sort 메서드에 전달하세요.
List<T> 클래스의 형식별 구현을 사용하는 것이 ArrayList 클래스를 사용하거나 강력한 형식의 래퍼 컬렉션을 직접 작성하는 것보다 유리합니다. 구현이 .NET에서 이미 수행하는 작업을 수행해야 하고 .NET 런타임은 구현에서 수행할 수 없는 일반적인 중간 언어 코드와 메타데이터를 공유할 수 있기 때문입니다.
F# 고려 사항
클래스는 List<T> F# 코드에서 자주 사용되지 않습니다. 대신 목록은 변경할 수 없는 단일 연결 리스트로 일반적으로 선호됩니다. F# List 은 순서가 지정되고 변경할 수 없는 일련의 값을 제공하며 기능 스타일 개발에 사용할 수 있도록 지원됩니다. F#에서 List<T> 클래스를 사용할 때는 보통 F# 목록과의 명명 충돌을 피하기 위해 ResizeArray<'T> 형식 약어로 참조됩니다.
생성자
| Name | Description |
|---|---|
| List<T>() |
비어 있고 기본 초기 용량이 List<T> 있는 클래스의 새 인스턴스를 초기화합니다. |
| List<T>(IEnumerable<T>) |
지정된 컬렉션에서 복사된 요소를 포함하고 복사된 요소 수를 List<T> 수용할 수 있는 충분한 용량이 있는 클래스의 새 인스턴스를 초기화합니다. |
| List<T>(Int32) |
비어 있고 지정된 초기 용량을 List<T> 가진 클래스의 새 인스턴스를 초기화합니다. |
속성
| Name | Description |
|---|---|
| Capacity |
크기 조정 없이 내부 데이터 구조에서 보유할 수 있는 요소의 총 수를 가져오거나 설정합니다. |
| Count |
에 포함된 List<T>요소 수를 가져옵니다. |
| Item[Int32] |
지정된 인덱스에서 요소를 가져오거나 설정합니다. |
메서드
| Name | Description |
|---|---|
| Add(T) |
의 끝에 개체를 추가합니다 List<T>. |
| AddRange(IEnumerable<T>) |
지정된 컬렉션의 요소를 .의 List<T>끝에 추가합니다. |
| AsReadOnly() |
현재 컬렉션에 대한 읽기 전용 ReadOnlyCollection<T> 래퍼를 반환합니다. |
| BinarySearch(Int32, Int32, T, IComparer<T>) |
지정된 비교자를 사용하여 정렬된 List<T> 요소의 범위에서 요소를 검색하고 요소의 인덱스(0부터 시작하는 인덱스)를 반환합니다. |
| BinarySearch(T, IComparer<T>) |
지정된 비교자를 사용하여 정렬된 List<T> 전체 요소를 검색하고 요소의 인덱스(0부터 시작하는 인덱스)를 반환합니다. |
| BinarySearch(T) |
기본 비교자를 사용하여 정렬된 List<T> 요소 전체를 검색하고 요소의 인덱스(0부터 시작하는 인덱스)를 반환합니다. |
| Clear() |
에서 모든 요소를 List<T>제거합니다. |
| Contains(T) |
요소가 .에 List<T>있는지 여부를 확인합니다. |
| ConvertAll<TOutput>(Converter<T,TOutput>) |
현재 List<T> 요소를 다른 형식으로 변환하고 변환된 요소가 포함된 목록을 반환합니다. |
| CopyTo(Int32, T[], Int32, Int32) |
대상 배열의 지정된 인덱스에서 시작하여 호환되는 1차원 배열로 요소 List<T> 범위를 복사합니다. |
| CopyTo(T[], Int32) |
대상 배열의 지정된 인덱스에서 시작하여 전체 List<T> 호환되는 1차원 배열에 복사합니다. |
| CopyTo(T[]) |
대상 배열의 시작 부분에서 시작하여 호환되는 1차원 배열에 전체를 List<T> 복사합니다. |
| 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부터 시작하는 인덱스(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, Int32, Int32) |
지정된 개체를 검색하고 지정된 인덱스에서 시작하여 지정된 개수의 요소를 포함하는 요소 List<T> 범위 내에서 처음 발생하는 인덱스(0부터 시작)를 반환합니다. |
| IndexOf(T, Int32) |
지정한 개체를 검색하고 지정된 인덱스에서 마지막 요소까지 확장되는 요소 List<T> 범위 내에서 첫 번째 항목의 인덱스(0부터 시작)를 반환합니다. |
| IndexOf(T) |
지정된 개체를 검색하고 전체 List<T>에서 처음 발생한 인덱스(0부터 시작)를 반환합니다. |
| Insert(Int32, T) |
지정된 인덱스에 요소를 List<T> 삽입합니다. |
| InsertRange(Int32, IEnumerable<T>) |
컬렉션의 List<T> 요소를 지정된 인덱스에 삽입합니다. |
| LastIndexOf(T, Int32, Int32) |
지정된 개체를 검색하고 지정된 개수의 요소를 포함하고 지정된 인덱스에서 끝나는 요소 List<T> 범위 내에서 마지막으로 발생한 인덱스(0부터 시작하는 인덱스)를 반환합니다. |
| LastIndexOf(T, Int32) |
지정된 개체를 검색하고 첫 번째 요소에서 지정된 인덱스로 확장되는 요소 List<T> 범위 내에서 마지막으로 발생한 항목의 인덱스(0부터 시작)를 반환합니다. |
| LastIndexOf(T) |
지정된 개체를 검색하고 전체 내에서 마지막으로 발생한 인덱스(0부터 시작하는 인덱스)를 반환합니다 List<T>. |
| 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>) |
지정된 요소를 사용하여 전체 List<T> 요소를 정렬합니다 Comparison<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> 모든 요소가 지정된 조건자에서 정의한 조건과 일치하는지 여부를 결정합니다. |
명시적 인터페이스 구현
| Name | Description |
|---|---|
| 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> 참조하세요.