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>
派生
属性
实现

示例

下面的示例演示如何添加、 删除和插入中的简单业务对象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 IEquitable.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 IEquitable.Equals method
        ' of the Part class, which checks the PartId for equality.
        Console.WriteLine(vbLf & "Contains(""1734""): {0}", parts.Contains(New Part() With { _
             .PartId = 1734, _
             .PartName = "" _
        }))

        ' Insert a new item at position 2.
        Console.WriteLine(vbLf & "Insert(2, ""1834"")")
        parts.Insert(2, New Part() With { _
             .PartName = "brake lever", _
             .PartId = 1834 _
        })


        'Console.WriteLine();
        For Each aPart As Part In parts
            Console.WriteLine(aPart)
        Next

        Console.WriteLine(vbLf & "Parts[3]: {0}", parts(3))

        Console.WriteLine(vbLf & "Remove(""1534"")")

        ' This will remove part 1534 even though the PartName is different,
        ' because the Equals method only checks PartId for equality.
        parts.Remove(New Part() With { _
             .PartId = 1534, _
             .PartName = "cogs" _
        })

        Console.WriteLine()
        For Each aPart As Part In parts
            Console.WriteLine(aPart)
        Next

        Console.WriteLine(vbLf & "RemoveAt(3)")
        ' This will remove part at index 3.
        parts.RemoveAt(3)

        Console.WriteLine()
        For Each aPart As Part In parts
            Console.WriteLine(aPart)
        Next
    End Sub
    '
    '        This example code produces the following output:
    '        ID: 1234   Name: crank arm
    '        ID: 1334   Name: chain ring
    '        ID: 1434   Name: regular seat
    '        ID: 1444   Name: banana seat
    '        ID: 1534   Name: cassette
    '        ID: 1634   Name: shift lever
    '
    '        Contains("1734"): False
    '
    '        Insert(2, "1834")
    '        ID: 1234   Name: crank arm
    '        ID: 1334   Name: chain ring
    '        ID: 1834   Name: brake lever
    '        ID: 1434   Name: regular seat
    '        ID: 1444   Name: banana seat
    '        ID: 1534   Name: cassette
    '        ID: 1634   Name: shift lever
    '
    '        Parts[3]: ID: 1434   Name: regular seat
    '
    '        Remove("1534")
    '
    '        ID: 1234   Name: crank arm
    '        ID: 1334   Name: chain ring
    '        ID: 1834   Name: brake lever
    '        ID: 1434   Name: regular seat
    '        ID: 1444   Name: banana seat
    '        ID: 1634   Name: shift lever
    '   '
    '        RemoveAt(3)
    '
    '        ID: 1234   Name: crank arm
    '        ID: 1334   Name: chain ring
    '        ID: 1834   Name: brake lever
    '        ID: 1444   Name: banana seat
    '        ID: 1634   Name: shift lever
    '        

End Class

// Simple business object. A PartId is used to identify the type of part  
// but the part name can change.  
[<CustomEquality; NoComparison>]
type Part = { PartId : int ; mutable PartName : string } with
    override this.GetHashCode() = hash this.PartId
    override this.Equals(other) =
        match other with
        | :? Part as p -> this.PartId = p.PartId
        | _ -> false
    override this.ToString() = sprintf "ID: %i   Name: %s" this.PartId this.PartName

[<EntryPoint>]
let main argv = 
    // We refer to System.Collections.Generic.List<'T> by its type 
    // abbreviation ResizeArray<'T> to avoid conflicts with the F# List module.    
    // Note: In F# code, F# linked lists are usually preferred over
    // ResizeArray<'T> when an extendable collection is required.
    let parts = ResizeArray<_>()
    parts.Add({PartName = "crank arm" ; PartId = 1234})
    parts.Add({PartName = "chain ring"; PartId = 1334 })
    parts.Add({PartName = "regular seat"; PartId = 1434 })
    parts.Add({PartName = "banana seat"; PartId = 1444 })
    parts.Add({PartName = "cassette"; PartId = 1534 })
    parts.Add({PartName = "shift lever"; PartId = 1634 })

    // Write out the parts in the ResizeArray.  This will call the overridden ToString method
    // in the Part type
    printfn ""
    parts |> Seq.iter (fun p -> printfn "%O" p)

    // Check the ResizeArray for part #1734. This calls the IEquatable.Equals method 
    // of the Part type, which checks the PartId for equality.    
    printfn "\nContains(\"1734\"): %b" (parts.Contains({PartId=1734; PartName=""}))
    
    // Insert a new item at position 2.
    printfn "\nInsert(2, \"1834\")"
    parts.Insert(2, { PartName = "brake lever"; PartId = 1834 })

    // Write out all parts
    parts |> Seq.iter (fun p -> printfn "%O" p)

    printfn "\nParts[3]: %O" parts.[3]

    printfn "\nRemove(\"1534\")"
    // This will remove part 1534 even though the PartName is different, 
    // because the Equals method only checks PartId for equality.
    // Since Remove returns true or false, we need to ignore the result
    parts.Remove({PartId=1534; PartName="cogs"}) |> ignore

    // Write out all parts
    printfn ""
    parts |> Seq.iter (fun p -> printfn "%O" p)

    printfn "\nRemoveAt(3)"
    // This will remove the part at index 3.
    parts.RemoveAt(3)

    // Write out all parts
    printfn ""
    parts |> Seq.iter (fun p -> printfn "%O" p)

    0 // return an integer exit code

下面的示例演示一些属性和方法的List<T>字符串类型的泛型类。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 default constructor is used to create a list of strings with the default capacity. Capacity显示属性,然后Add方法用于将添加多个项。The 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.

Contains方法用于测试的列表中的项是否存在Insert方法用于插入新项中间列表中,然后再次显示列表的内容。The 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.

TrimExcess方法用于减少容量以匹配计数,并CapacityCount属性将显示。The 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方法用于从列表中,删除所有项并CapacityCount属性将显示。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
 */
using System;
using System.Collections.Generic;

public class Example
{
    public static void Main()
    {
        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
    *)

注解

List<T>类是等效的泛型ArrayList类。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>通过使用AddAddRange方法。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.

  • 等方法ContainsIndexOfLastIndexOf,和Remove列表元素使用相等比较器。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实现IEquatable<T>泛型接口,则相等比较器是Equals(T)接口; 方法的默认相等比较器是为Object.Equals(Object)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>之前执行的操作 (如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>对象,可以通过设置增加到 20 亿元素在 64 位系统上的最大容量enabled的属性 <gcAllowVeryLargeObjects> configuration 元素true中运行时环境。.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. 如果引用类型用于类型TList<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>泛型接口,以防止BinarySearchSort中装箱列表元素的方法。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>对象传递给BinarySearchSort方法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 框架的用途,且公共语言运行时可以共享 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

List<T>类用于不常在F#代码。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>类通常将按引用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>)

返回DataTable,其中包含的副本DataRow对象,给定输入IEnumerable<T>对象的泛型参数TDataRowReturns 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到指定的对象DataTable,给定输入IEnumerable<T>对象的泛型参数TDataRowCopies 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到指定的对象DataTable,给定输入IEnumerable<T>对象的泛型参数TDataRowCopies 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)

将转换IEnumerableIQueryableConverts 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.

另请参阅