List<T> List<T> List<T> List<T> Class

定義

表示可以依照索引存取的強型別物件清單。Represents a strongly typed list of objects that can be accessed by index. 提供搜尋、排序和管理清單的方法。Provides methods to search, sort, and manipulate lists.

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
[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 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)

類型參數

T

清單中項目的類型。The type of elements in the list.

繼承
List<T>List<T>List<T>List<T>
衍生
屬性
實作

範例

注意

本文中的某些 C# 範例會在 Try.NET 內嵌程式碼執行器和測試區執行。Some of the C# examples in this article run in the Try.NET inline code runner and playground. 請選取 [執行] 按鈕 (若該按鈕存在) 以在互動式視窗中執行範例。When present, select the Run button to run an example in an interactive window. 執行程式碼之後,您便可以修改它,並再選取一次 [執行] 來執行修改過的程式碼。Once you execute the code, you can modify it and run the modified code by selecting Run again. 修改過的程式碼會在互動式視窗中執行,或是如果編譯失敗的話,互動式視窗會顯示所有 C# 編譯器錯誤訊息。The modified code either runs in the interactive window or, if compilation fails, the interactive window displays all C# compiler error messages.

下列範例示範如何在中List<T>加入、移除和插入簡單的商務物件。The following example demonstrates how to add, remove, and insert a simple business object in a 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

下列範例會示範類型為 string 之List<T>泛型類別的數個屬性和方法。The following example demonstrates several properties and methods of the List<T> generic class of type string. (如需複雜類型的List<T>範例, Contains請參閱方法)。(For an example of a List<T> of complex types, see the Contains method.)

無參數的函式是用來建立具有預設容量的字串清單。The parameterless constructor is used to create a list of strings with the default capacity. 隨即顯示Add屬性, 然後使用方法來新增數個專案。 CapacityThe Capacity property is displayed and then the Add method is used to add several items. 系統會列出這些專案, 且Capacity屬性會Count與屬性一起顯示, 以顯示所需的容量已增加。The items are listed, and the Capacity property is displayed again, along with the Count property, to show that the capacity has been increased as needed.

方法可用來測試清單中的專案是否存在Insert , 方法是用來在清單中間插入新專案, 而清單的內容則會再次顯示。 ContainsThe Contains method is used to test for the presence of an item in the list, the Insert method is used to insert a new item in the middle of the list, and the contents of the list are displayed again.

預設Item[Int32]屬性 (中C#的索引子) 是用來抓取專案, Remove方法是用來移除稍早加入之重複專案的第一個實例, 並再次顯示內容。The default Item[Int32] property (the indexer in C#) is used to retrieve an item, the Remove method is used to remove the first instance of the duplicate item added earlier, and the contents are displayed again. Remove方法一律會移除第一個遇到的實例。The Remove method always removes the first instance it encounters.

方法是用來減少符合計數的容量, Capacity並顯示和Count屬性。 TrimExcessThe TrimExcess method is used to reduce the capacity to match the count, and the Capacity and Count properties are displayed. 如果未使用的容量已少於總容量的 10%, 此清單就不會重新調整大小。If the unused capacity had been less than 10 percent of total capacity, the list would not have been resized.

最後, Clear使用方法來移除清單中的所有專案, Capacity並顯示和Count屬性。Finally, the Clear method is used to remove all items from the list, and the Capacity and Count properties are displayed.

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
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
    *)

備註

類別是ArrayList類別的泛型對等用法。 List<T>The List<T> class is the generic equivalent of the ArrayList class. 它會使用大小會視需要動態增加的陣列, 來執行泛型介面。IList<T>It implements the IList<T> generic interface by using an array whose size is dynamically increased as required.

您可以List<T> Add使用或AddRange方法, 將專案加入至。You can add items to a List<T> by using the Add or AddRange methods.

List<T>類別會同時使用相等比較子和排序比較子。The List<T> class uses both an equality comparer and an ordering comparer.

  • 方法 ( Contains例如、 IndexOfLastIndexOfRemove ) 會使用清單元素的相等比較子。Methods such as Contains, IndexOf, LastIndexOf, and Remove use an equality comparer for the list elements. 類型T的預設相等比較子會依照下列方式決定。The default equality comparer for type T is determined as follows. 如果類型T Equals(T)會執行Object.Equals(Object)泛型介面, 則相等比較子會是該介面的方法, 否則, 預設的相等比較子是。 IEquatable<T>If type T implements the IEquatable<T> generic interface, then the equality comparer is the Equals(T) method of that interface; otherwise, the default equality comparer is Object.Equals(Object).

  • BinarySearchSort之類的方法會針對清單元素使用排序比較子。Methods such as BinarySearch and Sort use an ordering comparer for the list elements. 類型T的預設比較子會依照下列方式決定。The default comparer for type T is determined as follows. 如果類型T會實IComparable<T>作為泛型介面, 則預設比較子會CompareTo(T)是該介面的方法, 否則, 如果T類型會執行IComparable非泛型介面, 則預設值為比較子是CompareTo(Object)該介面的方法。If type T implements the IComparable<T> generic interface, then the default comparer is the CompareTo(T) method of that interface; otherwise, if type T implements the nongeneric IComparable interface, then the default comparer is the CompareTo(Object) method of that interface. 如果類型T不會同時執行任何介面, 則沒有預設的比較子, 而且必須明確提供比較子或比較委派。If type T implements neither interface, then there is no default comparer, and a comparer or comparison delegate must be provided explicitly.

List<T>不保證會排序。The List<T> is not guaranteed to be sorted. 您必須List<T>先排序, 才能執行需要List<T>排序的BinarySearch作業 (例如)。You must sort the List<T> before performing operations (such as BinarySearch) that require the List<T> to be sorted.

這個集合中的專案可以使用整數索引來存取。Elements in this collection can be accessed using an integer index. 這個集合中的索引是以零為基底。Indexes in this collection are zero-based.

僅 .NET Framework: 對於非常大型List<T>的物件, 您可以在執行時間環境中, 將<gcAllowVeryLargeObjects> configuration 專案的enabled屬性設為true , 以將64位系統上的最大容量增加到2000000000個元素。.NET Framework only: For very large List<T> objects, you can increase the maximum capacity to 2 billion elements on a 64-bit system by setting the enabled attribute of the <gcAllowVeryLargeObjects> configuration element to true in the run-time environment.

List<T>接受null當做參考型別的有效值, 並允許重複的元素。List<T> accepts null as a valid value for reference types and allows duplicate elements.

如需List<T>類別的不可變版本, 請ImmutableList<T>參閱。For an immutable version of the List<T> class, see ImmutableList<T>.

效能考量Performance Considerations

在決定是否要使用List<T>ArrayList類別時, 兩者都有類似的List<T>功能, 請記住類別在大多數情況下會執行得更好, 而且是型別安全。In deciding whether to use the List<T> or ArrayList class, both of which have similar functionality, remember that the List<T> class performs better in most cases and is type safe. 如果T List<T>類別的型別使用了引用型別, 則這兩個類別的行為完全相同。If a reference type is used for type T of the List<T> class, the behavior of the two classes is identical. 不過, 如果型T別使用實值型別, 您就必須考慮執行和裝箱問題。However, if a value type is used for type T, you need to consider implementation and boxing issues.

如果實值型別用於型T別, 編譯器會特別針對該值型別產生List<T>類別的執行。If a value type is used for type T, the compiler generates an implementation of the List<T> class specifically for that value type. 這表示List<T>物件的清單元素不需要在可以使用專案之前進行裝箱, 而且在大約500清單元素建立之後, 儲存的記憶體不會裝箱清單元素大於用來產生類別的記憶體。That means a list element of a List<T> object does not have to be boxed before the element can be used, and after about 500 list elements are created the memory saved not boxing list elements is greater than the memory used to generate the class implementation.

請確定用於類型T的實數值型別會實作為IEquatable<T>泛型介面。Make certain the value type used for type T implements the IEquatable<T> generic interface. 如果不是, 則之類Contains的方法就Object.Equals(Object)必須呼叫方法, 這會將受影響的清單元素方塊。If not, methods such as Contains must call the Object.Equals(Object) method, which boxes the affected list element. 如果實值IComparable型別會實作為介面, 而且您擁有原始程式碼, 請同時IComparable<T>執行BinarySearch泛型介面, 以防止Sort和方法裝箱清單元素。If the value type implements the IComparable interface and you own the source code, also implement the IComparable<T> generic interface to prevent the BinarySearch and Sort methods from boxing list elements. 如果您沒有擁有原始程式碼, 請將IComparer<T>物件傳遞BinarySearch至和Sort方法If you do not own the source code, pass an IComparer<T> object to the BinarySearch and Sort methods

它的優點是您可以使用List<T>類別的型別特定實作為, 而不ArrayList使用類別, 或自行撰寫強型別包裝函式集合。It is to your advantage to use the type-specific implementation of the List<T> class instead of using the ArrayList class or writing a strongly typed wrapper collection yourself. 原因是您的實施必須執行 .NET Framework 的工作, 而 common language runtime 可以共用 Microsoft 中繼語言程式碼和中繼資料, 而您的實作為您的執行方式。The reason is your implementation must do what the .NET Framework does for you already, and the common language runtime can share Microsoft intermediate language code and metadata, which your implementation cannot.

F#考量F# Considerations

類別在程式碼中F#不常使用。 List<T>The List<T> class is used infrequently in F# code. 相反地,清單(也就是不可變的單一連結清單) 通常是慣用的。Instead, Lists, which are immutable, singly-linked lists, are typically preferred. F#清單會提供已排序、不可變的一系列值, 並且支援在功能樣式開發中使用。An F# List provides an ordered, immutable series of values, and is supported for use in functional-style development. 從F#使用時, List<T>類別通常是由collections.resizearray<t所參考, 不 > 類型縮寫, 以避免與清單的F#命名衝突When used from F#, the List<T> class is typically referred to by the ResizeArray<'T> type abbreviation to avoid naming conflicts with F# Lists

建構函式

List<T>() List<T>() List<T>() List<T>()

初始化 List<T> 類別的新執行個體,這個執行個體為空白且具有預設的初始容量。Initializes a new instance of the List<T> class that is empty and has the default initial capacity.

List<T>(IEnumerable<T>) List<T>(IEnumerable<T>) List<T>(IEnumerable<T>) List<T>(IEnumerable<T>)

初始化 List<T> 類別的新執行個體,其包含從指定之集合複製的元素,且具有容納複製之元素數目的足夠容量。Initializes a new instance of the List<T> class that contains elements copied from the specified collection and has sufficient capacity to accommodate the number of elements copied.

List<T>(Int32) List<T>(Int32) List<T>(Int32) List<T>(Int32)

為具有指定初始容量且為空的 List<T> 類別,初始化新的執行個體。Initializes a new instance of the List<T> class that is empty and has the specified initial capacity.

屬性

Capacity Capacity Capacity Capacity

在不需要調整大小之下,取得或設定內部資料結構可以保存的項目總數。Gets or sets the total number of elements the internal data structure can hold without resizing.

Count Count Count Count

取得 List<T> 中所包含的項目數。Gets the number of elements contained in the List<T>.

Item[Int32] Item[Int32] Item[Int32] Item[Int32]

在指定的索引位置上取得或設定項目。Gets or sets the element at the specified index.

方法

Add(T) Add(T) Add(T) Add(T)

將物件加入至 List<T> 的末端。Adds an object to the end of the List<T>.

AddRange(IEnumerable<T>) AddRange(IEnumerable<T>) AddRange(IEnumerable<T>) AddRange(IEnumerable<T>)

將特定集合的項目加入至 List<T> 的結尾。Adds the elements of the specified collection to the end of the List<T>.

AsReadOnly() AsReadOnly() AsReadOnly() AsReadOnly()

傳回目前集合的唯讀 ReadOnlyCollection<T> 包裝函式。Returns a read-only ReadOnlyCollection<T> wrapper for the current collection.

BinarySearch(Int32, Int32, T, IComparer<T>) BinarySearch(Int32, Int32, T, IComparer<T>) BinarySearch(Int32, Int32, T, IComparer<T>) BinarySearch(Int32, Int32, T, IComparer<T>)

使用指定的比較子在已經過排序之 List<T> 內,搜尋某範圍的項目,並傳回該項目以零為起始的索引。Searches a range of elements in the sorted List<T> for an element using the specified comparer and returns the zero-based index of the element.

BinarySearch(T) BinarySearch(T) BinarySearch(T) BinarySearch(T)

使用預設的比較子並傳回項目以零為起始的索引,來搜尋項目之整個排序的 List<T>Searches the entire sorted List<T> for an element using the default comparer and returns the zero-based index of the element.

BinarySearch(T, IComparer<T>) BinarySearch(T, IComparer<T>) BinarySearch(T, IComparer<T>) BinarySearch(T, IComparer<T>)

使用指定的比較子並傳回項目以零為起始的索引,來搜尋項目之整個排序的 List<T>Searches the entire sorted List<T> for an element using the specified comparer and returns the zero-based index of the element.

Clear() Clear() Clear() Clear()

移除 List<T> 中的所有項目。Removes all elements from the List<T>.

Contains(T) Contains(T) Contains(T) Contains(T)

判斷某項目是否在 List<T> 中。Determines whether an element is in the List<T>.

ConvertAll<TOutput>(Converter<T,TOutput>) ConvertAll<TOutput>(Converter<T,TOutput>) ConvertAll<TOutput>(Converter<T,TOutput>) ConvertAll<TOutput>(Converter<T,TOutput>)

將目前 List<T> 中的項目轉換成另一個類型,並傳回包含轉換過的項目清單。Converts the elements in the current List<T> to another type, and returns a list containing the converted elements.

CopyTo(Int32, T[], Int32, Int32) CopyTo(Int32, T[], Int32, Int32) CopyTo(Int32, T[], Int32, Int32) CopyTo(Int32, T[], Int32, Int32)

從目標陣列的指定索引處開始,將項目範圍從 List<T> 複製到相容的一維陣列。Copies a range of elements from the List<T> to a compatible one-dimensional array, starting at the specified index of the target array.

CopyTo(T[]) CopyTo(T[]) CopyTo(T[]) CopyTo(T[])

將整個 List<T> 複製到相容的一維陣列,從目標陣列的開頭開始。Copies the entire List<T> to a compatible one-dimensional array, starting at the beginning of the target array.

CopyTo(T[], Int32) CopyTo(T[], Int32) CopyTo(T[], Int32) CopyTo(T[], Int32)

從目標陣列的指定索引處開始,將整個 List<T> 複製到相容的一維陣列中。Copies the entire List<T> to a compatible one-dimensional array, starting at the specified index of the target array.

Equals(Object) Equals(Object) Equals(Object) Equals(Object)

判斷指定的物件是否等於目前的物件。Determines whether the specified object is equal to the current object.

(Inherited from Object)
Exists(Predicate<T>) Exists(Predicate<T>) Exists(Predicate<T>) Exists(Predicate<T>)

判斷 List<T> 是否包含符合指定之述詞 (Predicate) 所定義之條件的元素。Determines whether the List<T> contains elements that match the conditions defined by the specified predicate.

Find(Predicate<T>) Find(Predicate<T>) Find(Predicate<T>) Find(Predicate<T>)

搜尋符合指定之述詞所定義的條件之元素,並傳回整個 List<T> 內第一個相符的項目。Searches for an element that matches the conditions defined by the specified predicate, and returns the first occurrence within the entire List<T>.

FindAll(Predicate<T>) FindAll(Predicate<T>) FindAll(Predicate<T>) FindAll(Predicate<T>)

擷取符合指定之述詞所定義的條件之所有項目。Retrieves all the elements that match the conditions defined by the specified predicate.

FindIndex(Int32, Int32, Predicate<T>) FindIndex(Int32, Int32, Predicate<T>) FindIndex(Int32, Int32, Predicate<T>) FindIndex(Int32, Int32, Predicate<T>)

搜尋符合指定之述詞所定義的條件之項目,並傳回 List<T> 中從指定之索引開始,且包含指定之項目數目的項目範圍內第一個符合項目之以零為起始的索引。Searches for an element that matches the conditions defined by the specified predicate, and returns the zero-based index of the first occurrence within the range of elements in the List<T> that starts at the specified index and contains the specified number of elements.

FindIndex(Int32, Predicate<T>) FindIndex(Int32, Predicate<T>) FindIndex(Int32, Predicate<T>) FindIndex(Int32, Predicate<T>)

搜尋符合指定之述詞所定義的條件之項目,並傳回 List<T> 內 (從指定之索引延伸到最後一個項目),於某項目範圍中第一次出現之以零為起始的索引。Searches for an element that matches the conditions defined by the specified predicate, and returns the zero-based index of the first occurrence within the range of elements in the List<T> that extends from the specified index to the last element.

FindIndex(Predicate<T>) FindIndex(Predicate<T>) FindIndex(Predicate<T>) FindIndex(Predicate<T>)

搜尋符合指定之述詞所定義的條件之項目,並傳回整個 List<T> 內第一次出現之以零為起始的索引。Searches for an element that matches the conditions defined by the specified predicate, and returns the zero-based index of the first occurrence within the entire List<T>.

FindLast(Predicate<T>) FindLast(Predicate<T>) FindLast(Predicate<T>) FindLast(Predicate<T>)

搜尋符合指定之述詞所定義的條件之元素,並傳回整個 List<T> 內最後一個相符的項目。Searches for an element that matches the conditions defined by the specified predicate, and returns the last occurrence within the entire List<T>.

FindLastIndex(Int32, Int32, Predicate<T>) FindLastIndex(Int32, Int32, Predicate<T>) FindLastIndex(Int32, Int32, Predicate<T>) FindLastIndex(Int32, Int32, Predicate<T>)

搜尋符合指定之述詞所定義的條件之元素,並傳回 List<T> 中包含指定之元素數目,且結束於指定之索引的元素範圍內最後一個符合項目之以零起始的索引。Searches for an element that matches the conditions defined by the specified predicate, and returns the zero-based index of the last occurrence within the range of elements in the List<T> that contains the specified number of elements and ends at the specified index.

FindLastIndex(Int32, Predicate<T>) FindLastIndex(Int32, Predicate<T>) FindLastIndex(Int32, Predicate<T>) FindLastIndex(Int32, Predicate<T>)

搜尋符合指定之述詞所定義的條件之項目,並傳回 List<T> 中從第一個項目延伸到指定之索引的項目範圍內,最後一個符合項目之以零為起始的索引。Searches for an element that matches the conditions defined by the specified predicate, and returns the zero-based index of the last occurrence within the range of elements in the List<T> that extends from the first element to the specified index.

FindLastIndex(Predicate<T>) FindLastIndex(Predicate<T>) FindLastIndex(Predicate<T>) FindLastIndex(Predicate<T>)

搜尋符合指定之述詞所定義的條件之元素,並傳回整個 List<T> 內最後一個相符項目之以零起始的索引。Searches for an element that matches the conditions defined by the specified predicate, and returns the zero-based index of the last occurrence within the entire List<T>.

ForEach(Action<T>) ForEach(Action<T>) ForEach(Action<T>) ForEach(Action<T>)

List<T> 的每一個項目上執行指定之動作。Performs the specified action on each element of the List<T>.

GetEnumerator() GetEnumerator() GetEnumerator() GetEnumerator()

傳回在 List<T> 中逐一查看的列舉值。Returns an enumerator that iterates through the List<T>.

GetHashCode() GetHashCode() GetHashCode() GetHashCode()

做為預設雜湊函式。Serves as the default hash function.

(Inherited from Object)
GetRange(Int32, Int32) GetRange(Int32, Int32) GetRange(Int32, Int32) GetRange(Int32, Int32)

為來源 List<T> 中的項目範圍建立淺層複本。Creates a shallow copy of a range of elements in the source List<T>.

GetType() GetType() GetType() GetType()

取得目前執行個體的 TypeGets the Type of the current instance.

(Inherited from Object)
IndexOf(T) IndexOf(T) IndexOf(T) IndexOf(T)

搜尋指定的物件,並傳回整個 List<T> 中第一個相符項目之以零起始的索引。Searches for the specified object and returns the zero-based index of the first occurrence within the entire List<T>.

IndexOf(T, Int32) IndexOf(T, Int32) IndexOf(T, Int32) IndexOf(T, Int32)

List<T> 中從指定的索引開始到最後一個項目這段範圍內,搜尋指定的物件第一次出現的位置,並傳回其索引值 (索引以零起始)。Searches for the specified object and returns the zero-based index of the first occurrence within the range of elements in the List<T> that extends from the specified index to the last element.

IndexOf(T, Int32, Int32) IndexOf(T, Int32, Int32) IndexOf(T, Int32, Int32) IndexOf(T, Int32, Int32)

List<T> 中從指定索引開始且包含指定個數項目的範圍內,搜尋指定的物件第一次出現的位置,並傳回其索引值 (索引以零為起始)。Searches for the specified object and returns the zero-based index of the first occurrence within the range of elements in the List<T> that starts at the specified index and contains the specified number of elements.

Insert(Int32, T) Insert(Int32, T) Insert(Int32, T) Insert(Int32, T)

將項目插入至 List<T> 中指定的索引位置。Inserts an element into the List<T> at the specified index.

InsertRange(Int32, IEnumerable<T>) InsertRange(Int32, IEnumerable<T>) InsertRange(Int32, IEnumerable<T>) InsertRange(Int32, IEnumerable<T>)

將集合的項目插入位於指定索引的 List<T> 中。Inserts the elements of a collection into the List<T> at the specified index.

LastIndexOf(T) LastIndexOf(T) LastIndexOf(T) LastIndexOf(T)

搜尋指定的物件,並傳回整個 List<T> 中最後一個相符項目之以零起始的索引。Searches for the specified object and returns the zero-based index of the last occurrence within the entire List<T>.

LastIndexOf(T, Int32) LastIndexOf(T, Int32) LastIndexOf(T, Int32) LastIndexOf(T, Int32)

List<T> 中從第一個項目開始到指定的索引這段範圍內,搜尋指定的物件最後一次出現的位置,並傳回其索引值 (索引以零起始)。Searches for the specified object and returns the zero-based index of the last occurrence within the range of elements in the List<T> that extends from the first element to the specified index.

LastIndexOf(T, Int32, Int32) LastIndexOf(T, Int32, Int32) LastIndexOf(T, Int32, Int32) LastIndexOf(T, Int32, Int32)

List<T> 中包含指定個數項目且結尾位於指定索引的範圍內,搜尋指定的物件最後一次出現的位置,並傳回其索引值 (索引以零為起始)。Searches for the specified object and returns the zero-based index of the last occurrence within the range of elements in the List<T> that contains the specified number of elements and ends at the specified index.

MemberwiseClone() MemberwiseClone() MemberwiseClone() MemberwiseClone()

建立目前 Object 的淺層複本 (Shallow Copy)。Creates a shallow copy of the current Object.

(Inherited from Object)
Remove(T) Remove(T) Remove(T) Remove(T)

List<T> 移除特定物件之第一個符合的元素。Removes the first occurrence of a specific object from the List<T>.

RemoveAll(Predicate<T>) RemoveAll(Predicate<T>) RemoveAll(Predicate<T>) RemoveAll(Predicate<T>)

移除符合指定的述詞所定義之條件的所有項目。Removes all the elements that match the conditions defined by the specified predicate.

RemoveAt(Int32) RemoveAt(Int32) RemoveAt(Int32) RemoveAt(Int32)

移除 List<T> 之指定索引處的項目。Removes the element at the specified index of the List<T>.

RemoveRange(Int32, Int32) RemoveRange(Int32, Int32) RemoveRange(Int32, Int32) RemoveRange(Int32, Int32)

List<T> 移除的項目範圍。Removes a range of elements from the List<T>.

Reverse() Reverse() Reverse() Reverse()

反轉整個 List<T> 中項目的順序。Reverses the order of the elements in the entire List<T>.

Reverse(Int32, Int32) Reverse(Int32, Int32) Reverse(Int32, Int32) Reverse(Int32, Int32)

反向指定範圍中項目的順序。Reverses the order of the elements in the specified range.

Sort() Sort() Sort() Sort()

使用預設比較子來排序在整個 List<T> 中的項目。Sorts the elements in the entire List<T> using the default comparer.

Sort(Comparison<T>) Sort(Comparison<T>) Sort(Comparison<T>) Sort(Comparison<T>)

使用指定的 Comparison<T> 來排序在整個 List<T> 中的項目。Sorts the elements in the entire List<T> using the specified Comparison<T>.

Sort(IComparer<T>) Sort(IComparer<T>) Sort(IComparer<T>) Sort(IComparer<T>)

使用指定的比較子來排序在整個 List<T> 中的項目。Sorts the elements in the entire List<T> using the specified comparer.

Sort(Int32, Int32, IComparer<T>) Sort(Int32, Int32, IComparer<T>) Sort(Int32, Int32, IComparer<T>) Sort(Int32, Int32, IComparer<T>)

使用指定的比較子對 List<T> 中某段範圍內的項目進行排序。Sorts the elements in a range of elements in List<T> using the specified comparer.

ToArray() ToArray() ToArray() ToArray()

List<T> 的項目複製到新的陣列。Copies the elements of the List<T> to a new array.

ToString() ToString() ToString() ToString()

傳回代表目前物件的字串。Returns a string that represents the current object.

(Inherited from Object)
TrimExcess() TrimExcess() TrimExcess() TrimExcess()

將容量設為 List<T> 中項目的實際數目,如果該數目小於臨界值。Sets the capacity to the actual number of elements in the List<T>, if that number is less than a threshold value.

TrueForAll(Predicate<T>) TrueForAll(Predicate<T>) TrueForAll(Predicate<T>) TrueForAll(Predicate<T>)

判斷 List<T> 中的每一個項目是否符合指定之述詞所定義的條件。Determines whether every element in the List<T> matches the conditions defined by the specified predicate.

明確介面實作

ICollection.CopyTo(Array, Int32) ICollection.CopyTo(Array, Int32) ICollection.CopyTo(Array, Int32) ICollection.CopyTo(Array, Int32)

從特定的 ICollection 索引開始,將 Array 的項目複製到 ArrayCopies the elements of the ICollection to an Array, starting at a particular Array index.

ICollection.IsSynchronized ICollection.IsSynchronized ICollection.IsSynchronized ICollection.IsSynchronized

取得值,這個值表示對 ICollection 的存取是否同步 (安全執行緒)。Gets a value indicating whether access to the ICollection is synchronized (thread safe).

ICollection.SyncRoot ICollection.SyncRoot ICollection.SyncRoot ICollection.SyncRoot

取得可用以同步存取 ICollection 的物件。Gets an object that can be used to synchronize access to the ICollection.

ICollection<T>.IsReadOnly ICollection<T>.IsReadOnly ICollection<T>.IsReadOnly ICollection<T>.IsReadOnly

取得值,指出 ICollection<T> 是否唯讀。Gets a value indicating whether the ICollection<T> is read-only.

IEnumerable.GetEnumerator() IEnumerable.GetEnumerator() IEnumerable.GetEnumerator() IEnumerable.GetEnumerator()

傳回逐一查看集合的列舉值。Returns an enumerator that iterates through a collection.

IEnumerable<T>.GetEnumerator() IEnumerable<T>.GetEnumerator() IEnumerable<T>.GetEnumerator() IEnumerable<T>.GetEnumerator()

傳回逐一查看集合的列舉值。Returns an enumerator that iterates through a collection.

IList.Add(Object) IList.Add(Object) IList.Add(Object) IList.Add(Object)

將項目加入至 IListAdds an item to the IList.

IList.Contains(Object) IList.Contains(Object) IList.Contains(Object) IList.Contains(Object)

判斷 IList 是否包含特定值。Determines whether the IList contains a specific value.

IList.IndexOf(Object) IList.IndexOf(Object) IList.IndexOf(Object) IList.IndexOf(Object)

判斷 IList 中指定項目的索引。Determines the index of a specific item in the IList.

IList.Insert(Int32, Object) IList.Insert(Int32, Object) IList.Insert(Int32, Object) IList.Insert(Int32, Object)

將項目插入位於指定索引的 IListInserts an item to the IList at the specified index.

IList.IsFixedSize IList.IsFixedSize IList.IsFixedSize IList.IsFixedSize

取得值,指出 IList 是否有固定的大小。Gets a value indicating whether the IList has a fixed size.

IList.IsReadOnly IList.IsReadOnly IList.IsReadOnly IList.IsReadOnly

取得值,指出 IList 是否唯讀。Gets a value indicating whether the IList is read-only.

IList.Item[Int32] IList.Item[Int32] IList.Item[Int32] IList.Item[Int32]

在指定的索引位置上取得或設定項目。Gets or sets the element at the specified index.

IList.Remove(Object) IList.Remove(Object) IList.Remove(Object) IList.Remove(Object)

IList 移除特定物件之第一個符合的元素。Removes the first occurrence of a specific object from the IList.

擴充方法

CopyToDataTable<T>(IEnumerable<T>) CopyToDataTable<T>(IEnumerable<T>) CopyToDataTable<T>(IEnumerable<T>) CopyToDataTable<T>(IEnumerable<T>)

根據輸入 DataTable 物件 (其中泛型參數 TDataRow) 傳回包含 IEnumerable<T> 物件複本的 DataRowReturns a DataTable that contains copies of the DataRow objects, given an input IEnumerable<T> object where the generic parameter T is DataRow.

CopyToDataTable<T>(IEnumerable<T>, DataTable, LoadOption) CopyToDataTable<T>(IEnumerable<T>, DataTable, LoadOption) CopyToDataTable<T>(IEnumerable<T>, DataTable, LoadOption) CopyToDataTable<T>(IEnumerable<T>, DataTable, LoadOption)

根據輸入 DataRow 物件 (其中泛型參數 TDataTable),將 IEnumerable<T> 物件複製到指定的 DataRowCopies DataRow objects to the specified DataTable, given an input IEnumerable<T> object where the generic parameter T is DataRow.

CopyToDataTable<T>(IEnumerable<T>, DataTable, LoadOption, FillErrorEventHandler) CopyToDataTable<T>(IEnumerable<T>, DataTable, LoadOption, FillErrorEventHandler) CopyToDataTable<T>(IEnumerable<T>, DataTable, LoadOption, FillErrorEventHandler) CopyToDataTable<T>(IEnumerable<T>, DataTable, LoadOption, FillErrorEventHandler)

根據輸入 DataRow 物件 (其中泛型參數 TDataTable),將 IEnumerable<T> 物件複製到指定的 DataRowCopies DataRow objects to the specified DataTable, given an input IEnumerable<T> object where the generic parameter T is DataRow.

Cast<TResult>(IEnumerable) Cast<TResult>(IEnumerable) Cast<TResult>(IEnumerable) Cast<TResult>(IEnumerable)

IEnumerable 的項目轉換成指定的型別。Casts the elements of an IEnumerable to the specified type.

OfType<TResult>(IEnumerable) OfType<TResult>(IEnumerable) OfType<TResult>(IEnumerable) OfType<TResult>(IEnumerable)

根據指定的型別來篩選 IEnumerable 的項目。Filters the elements of an IEnumerable based on a specified type.

AsParallel(IEnumerable) AsParallel(IEnumerable) AsParallel(IEnumerable) AsParallel(IEnumerable)

啟用查詢的平行化作業。Enables parallelization of a query.

AsQueryable(IEnumerable) AsQueryable(IEnumerable) AsQueryable(IEnumerable) AsQueryable(IEnumerable)

IEnumerable 轉換成 IQueryableConverts an IEnumerable to an IQueryable.

Ancestors<T>(IEnumerable<T>) Ancestors<T>(IEnumerable<T>) Ancestors<T>(IEnumerable<T>) Ancestors<T>(IEnumerable<T>)

傳回包含來源集合中每個節點祖系的項目集合。Returns a collection of elements that contains the ancestors of every node in the source collection.

Ancestors<T>(IEnumerable<T>, XName) Ancestors<T>(IEnumerable<T>, XName) Ancestors<T>(IEnumerable<T>, XName) Ancestors<T>(IEnumerable<T>, XName)

傳回包含來源集合中每個節點祖系的已篩選項目集合。Returns a filtered collection of elements that contains the ancestors of every node in the source collection. 集合中只會包含具有相符之 XName 的項目。Only elements that have a matching XName are included in the collection.

DescendantNodes<T>(IEnumerable<T>) DescendantNodes<T>(IEnumerable<T>) DescendantNodes<T>(IEnumerable<T>) DescendantNodes<T>(IEnumerable<T>)

傳回來源集合中每個文件和項目之子代節點的集合。Returns a collection of the descendant nodes of every document and element in the source collection.

Descendants<T>(IEnumerable<T>) Descendants<T>(IEnumerable<T>) Descendants<T>(IEnumerable<T>) Descendants<T>(IEnumerable<T>)

傳回包含來源集合中每個項目和文件之子代項目的項目集合。Returns a collection of elements that contains the descendant elements of every element and document in the source collection.

Descendants<T>(IEnumerable<T>, XName) Descendants<T>(IEnumerable<T>, XName) Descendants<T>(IEnumerable<T>, XName) Descendants<T>(IEnumerable<T>, XName)

傳回已篩選的項目集合,其中包含來源集合中每個項目和文件的子代項目。Returns a filtered collection of elements that contains the descendant elements of every element and document in the source collection. 集合中只會包含具有相符之 XName 的項目。Only elements that have a matching XName are included in the collection.

Elements<T>(IEnumerable<T>) Elements<T>(IEnumerable<T>) Elements<T>(IEnumerable<T>) Elements<T>(IEnumerable<T>)

傳回來源集合中每個項目和文件的子項目集合。Returns a collection of the child elements of every element and document in the source collection.

Elements<T>(IEnumerable<T>, XName) Elements<T>(IEnumerable<T>, XName) Elements<T>(IEnumerable<T>, XName) Elements<T>(IEnumerable<T>, XName)

傳回來源集合中每個項目和文件的已篩選子項目集合。Returns a filtered collection of the child elements of every element and document in the source collection. 集合中只會包含具有相符之 XName 的項目。Only elements that have a matching XName are included in the collection.

InDocumentOrder<T>(IEnumerable<T>) InDocumentOrder<T>(IEnumerable<T>) InDocumentOrder<T>(IEnumerable<T>) InDocumentOrder<T>(IEnumerable<T>)

傳回包含來源集合中所有節點的節點集合,依據文件順序來排序。Returns a collection of nodes that contains all nodes in the source collection, sorted in document order.

Nodes<T>(IEnumerable<T>) Nodes<T>(IEnumerable<T>) Nodes<T>(IEnumerable<T>) Nodes<T>(IEnumerable<T>)

傳回來源集合中每個文件和項目的子節點集合。Returns a collection of the child nodes of every document and element in the source collection.

Remove<T>(IEnumerable<T>) Remove<T>(IEnumerable<T>) Remove<T>(IEnumerable<T>) Remove<T>(IEnumerable<T>)

在來源集合中,從每一個節點的父節點移除這些節點。Removes every node in the source collection from its parent node.

適用於

執行緒安全性

此類型的Shared公用靜態 (在 Visual Basic 中) 成員是安全線程。Public static (Shared in Visual Basic) members of this type are thread safe. 不保證任何執行個體成員是安全執行緒。Any instance members are not guaranteed to be thread safe.

在上List<T>執行多個讀取作業是安全的, 但如果在讀取時修改了集合, 就可能會發生問題。It is safe to perform multiple read operations on a List<T>, but issues can occur if the collection is modified while it's being read. 為確保執行緒安全, 請在讀取或寫入作業期間鎖定集合。To ensure thread safety, lock the collection during a read or write operation. 若要讓多個執行緒能夠存取集合以進行讀取和寫入, 您必須執行自己的同步處理。To enable a collection to be accessed by multiple threads for reading and writing, you must implement your own synchronization. 針對具有內建同步處理的集合, 請參閱System.Collections.Concurrent命名空間中的類別。For collections with built-in synchronization, see the classes in the System.Collections.Concurrent namespace. 如需原本就安全線程的替代方法, ImmutableList<T>請參閱類別。For an inherently thread-safe alternative, see the ImmutableList<T> class.

另請參閱