List<T>.Capacity Propriété

Définition

Obtient ou définit le nombre total des éléments que la structure de données interne peut contenir sans redimensionnement.

public:
 property int Capacity { int get(); void set(int value); };
public int Capacity { get; set; }
member this.Capacity : int with get, set
Public Property Capacity As Integer

Valeur de propriété

Nombre d'éléments que List<T> peut contenir avant que le redimensionnement soit nécessaire.

Exceptions

La valeur affectée à Capacity est inférieure à Count.

Il n’y a pas assez de mémoire disponible sur le système.

Exemples

L’exemple suivant montre comment case activée la capacité et le nombre d’un List<T> qui contient un objet métier simple, et illustre l’utilisation de la méthode pour supprimer une TrimExcess capacité supplémentaire.

using System;
using System.Collections.Generic;
// Simple business object. A PartId is used to identify a part
// but the part name be different for the same Id.
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 base.GetHashCode();
    }
    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()
    {
        List<Part> parts = new List<Part>();

        Console.WriteLine("\nCapacity: {0}", parts.Capacity);

        parts.Add(new Part() { PartName = "crank arm", PartId = 1234 });
        parts.Add(new Part() { PartName = "chain ring", PartId = 1334 });
        parts.Add(new Part() { PartName = "seat", PartId = 1434 });
        parts.Add(new Part() { PartName = "cassette", PartId = 1534 });
        parts.Add(new Part() { PartName = "shift lever", PartId = 1634 }); ;

        Console.WriteLine();
        foreach (Part aPart in parts)
        {
            Console.WriteLine(aPart);
        }

        Console.WriteLine("\nCapacity: {0}", parts.Capacity);
        Console.WriteLine("Count: {0}", parts.Count);

        parts.TrimExcess();
        Console.WriteLine("\nTrimExcess()");
        Console.WriteLine("Capacity: {0}", parts.Capacity);
        Console.WriteLine("Count: {0}", parts.Count);

        parts.Clear();
        Console.WriteLine("\nClear()");
        Console.WriteLine("Capacity: {0}", parts.Capacity);
        Console.WriteLine("Count: {0}", parts.Count);
    }
    /*
     This code example produces the following output.
            Capacity: 0

            ID: 1234   Name: crank arm
            ID: 1334   Name: chain ring
            ID: 1434   Name: seat
            ID: 1534   Name: cassette
            ID: 1634   Name: shift lever

            Capacity: 8
            Count: 5

            TrimExcess()
            Capacity: 5
            Count: 5

            Clear()
            Capacity: 5
            Count: 0
     */
}
Imports System.Collections.Generic

' Simple business object. A PartId is used to identify a 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 MyBase.GetHashCode()
    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()
        Dim parts As New List(Of Part)()

        Console.WriteLine(vbLf & "Capacity: {0}", parts.Capacity)

        ' 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 _
        })



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

        Console.WriteLine(vbLf & "Capacity: {0}", parts.Capacity)
        Console.WriteLine("Count: {0}", parts.Count)

        parts.TrimExcess()
        Console.WriteLine(vbLf & "TrimExcess()")
        Console.WriteLine("Capacity: {0}", parts.Capacity)
        Console.WriteLine("Count: {0}", parts.Count)

        parts.Clear()
        Console.WriteLine(vbLf & "Clear()")
        Console.WriteLine("Capacity: {0}", parts.Capacity)
        Console.WriteLine("Count: {0}", parts.Count)
    End Sub
    '
    '     This code example produces the following output. 
    '            Capacity: 0
    '
    '            ID: 1234   Name: crank arm
    '            ID: 1334   Name: chain ring
    '            ID: 1434   Name: seat
    '            ID: 1534   Name: cassette
    '            ID: 1634   Name: shift lever
    '
    '            Capacity: 8
    '            Count: 6
    '
    '            TrimExcess()
    '            Capacity: 6
    '            Count: 6
    '
    '            Clear()
    '            Capacity: 6
    '            Count: 0
    '     

End Class

L’exemple suivant montre la Capacity propriété à plusieurs points de la vie d’une liste. Le constructeur sans paramètre est utilisé pour créer une liste de chaînes d’une capacité de 0, et la Capacity propriété est affichée pour illustrer cela. Une fois que la Add méthode a été utilisée pour ajouter plusieurs éléments, les éléments sont répertoriés, puis la Capacity propriété est à nouveau affichée, avec la Count propriété, pour montrer que la capacité a été augmentée en fonction des besoins.

La Capacity propriété s’affiche à nouveau après l’utilisation de la TrimExcess méthode pour réduire la capacité à correspondre au nombre. Enfin, la Clear méthode est utilisée pour supprimer tous les éléments de la liste, et les Capacity propriétés et Count sont à nouveau affichées.

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

Remarques

Capacity est le nombre d’éléments que le peut stocker avant que le List<T> redimensionnement ne soit requis, tandis que Count est le nombre d’éléments qui se trouvent réellement dans le List<T>.

Capacity est toujours supérieur ou égal à Count. Si Count elle dépasse lors de Capacity l’ajout d’éléments, la capacité est augmentée en réaffectant automatiquement le tableau interne avant de copier les anciens éléments et d’ajouter les nouveaux éléments.

Si la capacité est considérablement supérieure au nombre et que vous souhaitez réduire la mémoire utilisée par , vous pouvez réduire la List<T>capacité en appelant la TrimExcess méthode ou en définissant explicitement la Capacity propriété sur une valeur inférieure. Lorsque la valeur de Capacity est définie explicitement, le tableau interne est également réaffecté pour prendre en charge la capacité spécifiée, et tous les éléments sont copiés.

La récupération de la valeur de cette propriété est une opération O(1) ; la définition de la propriété est une opération O(n), où n est la nouvelle capacité.

S’applique à

Voir aussi