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 method.)
無參數建構函式可用來建立具有預設容量的字串清單。 屬性 Capacity 隨即顯示,然後使用 Add 方法來新增數個專案。 系統會列出專案,並 Capacity 再次顯示 屬性以及 Count 屬性,以顯示容量已視需要增加。
方法 Contains 可用來測試清單中是否有專案, Insert 方法是用來在清單中間插入新專案,並再次顯示清單的內容。
Item[]預設屬性 (C# ) 中的索引子是用來擷取專案, Remove 方法是用來移除稍早新增之重複專案的第一個實例,並再次顯示內容。 方法 Remove 一律會移除它遇到的第一個實例。
方法 TrimExcess 可用來減少容量以符合計數,並 Capacity 顯示 和 Count 屬性。 如果未使用的容量小於總容量的 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 方法,將專案新增至 。 AddList<T>
類別 List<T> 同時使用相等比較子和排序比較子。
、 IndexOf 、 LastIndexOf 和 Remove 之類的 Contains 方法會針對清單專案使用相等比較子。 類型的預設相等比較子
T
會依下列方式決定。 如果類型T
實作 IEquatable<T> 泛型介面,則相等比較子是 Equals(T) 該介面的 方法,否則預設相等比較子為 Object.Equals(Object) 。和 等 BinarySearch 方法會 Sort 針對清單專案使用排序比較子。 類型
T
的預設比較子會依下列方式決定。 如果類型T
實作 IComparable<T> 泛型介面,則預設比較子是 CompareTo(T) 該介面的 方法;否則,如果類型T
實作非泛型 IComparable 介面,則預設比較子是 CompareTo(Object) 該介面的方法。 如果類型T
未實作兩個介面,則沒有預設比較子,而且必須明確提供比較子或比較委派。
List<T>不保證會排序 。 您必須先排序 List<T> ,才能執行作業 (,例如 BinarySearch 需要 List<T> 排序 的) 。
這個集合中的元素可以使用整數索引來存取。 此集合中的索引是以零起始。
僅.NET Framework:對於非常大 List<T> 的物件,您可以將 64 位系統上的最大容量增加到 200 億個元素,方法是在執行時間環境中將組態元素的 <gcAllowVeryLargeObjects>
屬性設定 enabled
為 true
。
List<T> 接受 null
作為參考型別的有效值,並允許重複的專案。
如需類別的 List<T> 不可變版本,請參閱 ImmutableList<T> 。
效能考量
在決定是否要使用 List<T> 或 ArrayList 類別時,兩者都有類似的功能,請記住,在大部分情況下,類別 List<T> 的執行效能更好,而且型別安全。 如果參考型別用於 類別的類型 T
List<T> ,則兩個類別的行為相同。 不過,如果實值型別用於 類型 T
,您需要考慮實作和 Boxing 問題。
如果實值型別用於 型 T
別,編譯器就會針對該實值型別產生類別的 List<T> 實作。 這表示物件的清單元素 List<T> 不需要在元素可以使用之前進行 Boxed,而且建立大約 500 個清單元素之後,不會使用 Boxing list 元素所儲存的記憶體大於用來產生類別實作的記憶體。
請確定用於類型的 T
IEquatable<T> 實作泛型介面的值型別。 如果沒有,這類 Contains 方法必須呼叫 Object.Equals(Object) 方法,以方塊受影響的清單專案。 如果實作 IComparable 介面且您擁有原始程式碼的實值型別,也實 IComparable<T> 作泛型介面,以防止 BinarySearch 和 Sort 方法將清單專案設為 Boxing 清單專案。 如果您沒有擁有原始程式碼,請將 物件傳遞 IComparer<T> 至 BinarySearch 和 Sort 方法
您的優點是使用 類別的 List<T> 型別特定實作,而不是使用 ArrayList 類別,或自行撰寫強型別包裝函式集合。 這是因為您的實作必須為您執行.NET Framework的功能,而 Common Language Runtime 可以共用您的實作無法執行的 Microsoft 中繼語言程式碼和中繼資料。
F# 考慮
類別 List<T> 在 F# 程式碼中不常使用。 相反 地,通常是慣用不可變、單向連結清單的清單。 F# List
提供已排序且不可變的值系列,而且支援在功能樣式開發中使用。 從 F# 使用時, List<T> 類別通常是由 ResizeArray<'T>
類型縮寫所參考,以避免與 F# 清單發生命名衝突。
建構函式
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> 內,搜尋某範圍的項目,並傳回該項目以零為起始的索引。 |
BinarySearch(T) |
使用預設的比較子並傳回項目以零為起始的索引,來搜尋項目之整個排序的 List<T>。 |
BinarySearch(T, IComparer<T>) |
使用指定的比較子並傳回項目以零為起始的索引,來搜尋項目之整個排序的 List<T>。 |
Clear() |
移除 List<T> 中的所有項目。 |
Contains(T) |
判斷某項目是否在 List<T> 中。 |
ConvertAll<TOutput>(Converter<T,TOutput>) |
將目前 List<T> 中的項目轉換成另一個類型,並傳回包含轉換過的項目清單。 |
CopyTo(Int32, T[], Int32, Int32) |
從目標陣列的指定索引處開始,將項目範圍從 List<T> 複製到相容的一維陣列。 |
CopyTo(T[]) |
從目標陣列的開頭開始,將整個 List<T> 複製到相容的一維陣列。 |
CopyTo(T[], Int32) |
從目標陣列的指定索引處開始,將整個 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> 中從指定之索引開始,且包含指定之項目數目的項目範圍內第一個符合項目之以零為起始的索引。 |
FindIndex(Int32, Predicate<T>) |
搜尋符合指定之述詞所定義的條件之項目,並傳回 List<T> 內 (從指定之索引延伸到最後一個項目),於某項目範圍中第一次出現之以零為起始的索引。 |
FindIndex(Predicate<T>) |
搜尋符合指定之述詞所定義的條件之項目,並傳回整個 List<T> 內第一次出現之以零為起始的索引。 |
FindLast(Predicate<T>) |
搜尋符合指定之述詞所定義的條件之項目,並傳回整個 List<T> 內最後一個相符的項目。 |
FindLastIndex(Int32, Int32, Predicate<T>) |
搜尋符合指定之述詞所定義的條件之項目,並傳回 List<T> 中包含指定之項目數目,且結束於指定之索引的項目範圍內最後一個符合項目之以零為起始的索引。 |
FindLastIndex(Int32, Predicate<T>) |
搜尋符合指定之述詞所定義的條件之項目,並傳回 List<T> 中從第一個項目延伸到指定之索引的項目範圍內,最後一個符合項目之以零為起始的索引。 |
FindLastIndex(Predicate<T>) |
搜尋符合指定之述詞所定義的條件之項目,並傳回整個 List<T> 內最後一次出現之以為零起始的索引。 |
ForEach(Action<T>) |
在 List<T> 的每一個項目上執行指定之動作。 |
GetEnumerator() |
傳回在 List<T> 中逐一查看的列舉值。 |
GetHashCode() |
做為預設雜湊函式。 (繼承來源 Object) |
GetRange(Int32, Int32) |
為來源 List<T> 中的項目範圍建立淺層複本。 |
GetType() |
取得目前執行個體的 Type。 (繼承來源 Object) |
IndexOf(T) |
搜尋指定的物件,並傳回整個 List<T> 中第一個出現之以零為起始的索引。 |
IndexOf(T, Int32) |
在 List<T> 中從指定的索引開始到最後一個項目這段範圍內,搜尋指定的物件第一次出現的位置,並傳回其索引值 (索引以零為起始)。 |
IndexOf(T, Int32, Int32) |
在 List<T> 中從指定索引開始且包含指定個數項目的範圍內,搜尋指定的物件第一次出現的位置,並傳回其索引值 (索引以零為起始)。 |
Insert(Int32, T) |
將項目插入至 List<T> 中指定的索引位置。 |
InsertRange(Int32, IEnumerable<T>) |
將集合的項目插入位於指定索引的 List<T> 中。 |
LastIndexOf(T) |
搜尋指定的物件,並傳回整個 List<T> 中最後一個相符項目之以零為起始的索引。 |
LastIndexOf(T, Int32) |
在 List<T> 中從第一個項目開始到指定的索引這段範圍內,搜尋指定的物件最後一次出現的位置,並傳回其索引值 (索引以零為起始)。 |
LastIndexOf(T, Int32, Int32) |
在 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>) |
使用指定的 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 移除特定物件之第一個符合的元素。 |
擴充方法
適用於
執行緒安全性
Visual Basic 中的公用靜態 (Shared
) 此類型的成員是安全線程。 並非所有的執行個體成員都是安全執行緒。
在 上 List<T> 執行多個讀取作業是安全的,但如果正在讀取集合時修改集合,可能會發生問題。 為了確保執行緒安全,請在讀取或寫入作業期間鎖定集合。 若要讓多個執行緒存取集合以進行讀取和寫入,您必須實作自己的同步處理。 如需具有內建同步處理的集合,請參閱 命名空間中的 System.Collections.Concurrent 類別。 如需原本就安全線程的替代方法,請參閱 類別 ImmutableList<T> 。
另請參閱
意見反應
提交並檢視相關的意見反應