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.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诸如、IndexOf、和Remove等方法对列表元素使用相等比较器。 LastIndexOfMethods 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 CompareTo(T) T IComparable实现泛型接口, 则默认比较器是该接口的方法; 否则, 如果类型实现非泛型接口, 则默认值为IComparable<T>比较器是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>先对进行排序, 然后再执行需要BinarySearch排序的List<T>操作 (如)。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>的对象, 可以通过在运行时环境中enabled<gcAllowVeryLargeObjects>配置元素的属性设置为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 的操作, 并且公共语言运行时可以共享你的实现不能的 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 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> 是否包含与指定谓词所定义的条件相匹配的元素。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 的浅表副本。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 的元素复制到一个 Array 中。Copies 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)

将某项添加到 IList 中。Adds 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)

IList 中的指定索引处插入一个项。Inserts 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>)

在给定其泛型参数 TDataTable 的输入 DataRow 对象的情况下,返回包含 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)

在给定其泛型参数 TDataRow 的输入 DataTable 对象的情况下,将 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)

在给定其泛型参数 TDataRow 的输入 DataTable 对象的情况下,将 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.

另请参阅