Freigeben über


List<T> Konstruktoren

Definition

Initialisiert eine neue Instanz der List<T>-Klasse.

Überlädt

Name Beschreibung
List<T>()

Initialisiert eine neue Instanz der Klasse, die List<T> leer ist und über die Standardkapazität verfügt.

List<T>(IEnumerable<T>)

Initialisiert eine neue Instanz der List<T> Klasse, die Elemente enthält, die aus der angegebenen Auflistung kopiert wurden, und verfügt über ausreichende Kapazität, um die Anzahl der kopierten Elemente zu berücksichtigen.

List<T>(Int32)

Initialisiert eine neue Instanz der Klasse, die List<T> leer ist und über die angegebene Anfangskapazität verfügt.

List<T>()

Quelle:
List.cs
Quelle:
List.cs
Quelle:
List.cs
Quelle:
List.cs
Quelle:
List.cs

Initialisiert eine neue Instanz der Klasse, die List<T> leer ist und über die Standardkapazität verfügt.

public:
 List();
public List();
Public Sub New ()

Beispiele

Im folgenden Beispiel wird der parameterlose Konstruktor der List<T> generischen Klasse veranschaulicht. Der parameterlose Konstruktor erstellt eine Liste mit der Standardkapazität, wie durch anzeigen der Capacity Eigenschaft dargestellt.

Im Beispiel werden Elemente hinzugefügt, eingefügt und entfernt, die zeigen, wie sich die Kapazität ändert, während diese Methoden verwendet werden.

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

Partial Public Class Program
    Public Shared Sub ShowPlanets()
        Dim planets As New List(Of String)

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

        planets.Add("Mercury")
        planets.Add("Venus")
        planets.Add("Earth")
        planets.Add("Mars")
        planets.Add("Jupiter")

        Console.WriteLine()
        For Each planet As String In planets
            Console.WriteLine(planet)
        Next

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

        Console.WriteLine(vbLf & "Contains(""Mars""): {0}", _
            planets.Contains("Mars"))

        Console.WriteLine(vbLf & "Insert(2, ""Saturn"")")
        planets.Insert(2, "Saturn")

        Console.WriteLine()
        For Each planet As String In planets
            Console.WriteLine(planet)
        Next
        ' Shows how to access the list using the Item property.
        Console.WriteLine(vbLf & "planets(3): {0}", planets(3))
        Console.WriteLine(vbLf & "Remove(""Jupiter"")")
        planets.Remove("Jupiter")

        Console.WriteLine()
        For Each planet As String In planets
            Console.WriteLine(planet)
        Next

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

        planets.Clear()
        Console.WriteLine(vbLf & "Clear()")
        Console.WriteLine("Capacity: {0}", planets.Capacity)
        Console.WriteLine("Count: {0}", planets.Count)
    End Sub
End Class

' This code example produces the following output:
'
' Capacity: 0
'
' Mercury
' Venus
' Earth
' Mars
' Jupiter
'
' Capacity: 8
' Count: 5
'
' Contains("Mars"): True
'
' Insert(2, "Saturn")
'
' Mercury
' Venus
' Saturn
' Earth
' Mars
' Jupiter
'
' planets(3): Earth
'
' Remove("Jupiter")
'
' Mercury
' Venus
' Saturn
' Earth
' Mars
'
' 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
    *)

Hinweise

Die Kapazität eines Elements List<T> ist die Anzahl der Elemente, die aufbewahrt List<T> werden können. Wenn Elemente zu einem List<T>Element hinzugefügt werden, wird die Kapazität bei Bedarf automatisch erhöht, indem das interne Array neu zugeordnet wird.

Wenn die Größe der Auflistung geschätzt werden kann, wird mit dem List<T>(Int32) Konstruktor und der Angabe der anfänglichen Kapazität die Notwendigkeit beseitigt, eine Reihe von Größenänderungsvorgängen auszuführen, während Elemente zum Hinzufügen von Elementen hinzugefügt werden List<T>.

Die Kapazität kann durch Aufrufen der TrimExcess Methode oder durch explizites Festlegen der Capacity Eigenschaft verringert werden. Durch verringern der Kapazität wird der Arbeitsspeicher neu zuordnen und alle Elemente in der List<T>Datei kopiert.

Dieser Konstruktor ist ein O(1)-Vorgang.

Gilt für:

List<T>(IEnumerable<T>)

Quelle:
List.cs
Quelle:
List.cs
Quelle:
List.cs
Quelle:
List.cs
Quelle:
List.cs

Initialisiert eine neue Instanz der List<T> Klasse, die Elemente enthält, die aus der angegebenen Auflistung kopiert wurden, und verfügt über ausreichende Kapazität, um die Anzahl der kopierten Elemente zu berücksichtigen.

public:
 List(System::Collections::Generic::IEnumerable<T> ^ collection);
public List(System.Collections.Generic.IEnumerable<T> collection);
new System.Collections.Generic.List<'T> : seq<'T> -> System.Collections.Generic.List<'T>
Public Sub New (collection As IEnumerable(Of T))

Parameter

collection
IEnumerable<T>

Die Auflistung, deren Elemente in die neue Liste kopiert werden.

Ausnahmen

collection ist null.

Beispiele

Das folgende Beispiel veranschaulicht den List<T> Konstruktor und verschiedene Methoden der Klasse, die List<T> auf Bereiche reagieren. Ein Array von Zeichenfolgen wird erstellt und an den Konstruktor übergeben, wobei die Liste mit den Elementen des Arrays auffüllt wird. Die Capacity Eigenschaft wird dann angezeigt, um anzuzeigen, dass die anfängliche Kapazität genau das ist, was erforderlich ist, um die Eingabeelemente zu halten.

using System;
using System.Collections.Generic;

string[] input = { "Apple",
                   "Banana",
                   "Orange" };

List<string> fruits = new List<string>(input);

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

foreach (string fruit in fruits)
{
    Console.WriteLine(fruit);
}

Console.WriteLine("\nAddRange(fruits)");
fruits.AddRange(fruits);

Console.WriteLine();
foreach (string fruit in fruits)
{
    Console.WriteLine(fruit);
}

Console.WriteLine("\nRemoveRange(2, 2)");
fruits.RemoveRange(2, 2);

Console.WriteLine();
foreach (string fruit in fruits)
{
    Console.WriteLine(fruit);
}

input = new string[] { "Mango",
                       "Pineapple",
                       "Watermelon" };

Console.WriteLine("\nInsertRange(3, input)");
fruits.InsertRange(3, input);

Console.WriteLine();
foreach (string fruit in fruits)
{
    Console.WriteLine(fruit);
}

Console.WriteLine("\noutput = fruits.GetRange(2, 3).ToArray()");
string[] output = fruits.GetRange(2, 3).ToArray();

Console.WriteLine();
foreach (string fruit in output)
{
    Console.WriteLine(fruit);
}

/*
    This code example produces the following output:

    Capacity: 3

    Apple
    Banana
    Orange

    AddRange(fruits)

    Apple
    Banana
    Orange
    Apple
    Banana
    Orange

    RemoveRange(2, 2)

    Apple
    Banana
    Banana
    Orange

    InsertRange(3, input)

    Apple
    Banana
    Banana
    Mango
    Pineapple
    Watermelon
    Orange

    output = fruits.GetRange(2, 3).ToArray()

    Banana
    Mango
    Pineapple
*/
Imports System.Collections.Generic

Partial Public Class Program
    Public Shared Sub ShowFruits()

        Dim input() As String = { "Apple", _
                                  "Banana", _
                                  "Orange" }

        Dim fruits As New List(Of String)(input)

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

        For Each fruit As String In fruits
            Console.WriteLine(fruit)
        Next

        Console.WriteLine(vbLf & "AddRange(fruits)")
        fruits.AddRange(fruits)

        Console.WriteLine()
        For Each fruit As String In fruits
            Console.WriteLine(fruit)
        Next

        Console.WriteLine(vbLf & "RemoveRange(2, 2)")
        fruits.RemoveRange(2, 2)

        Console.WriteLine()
        For Each fruit As String In fruits
            Console.WriteLine(fruit)
        Next

        input = New String() { "Mango", _
                               "Pineapple", _
                               "Watermelon" }

        Console.WriteLine(vbLf & "InsertRange(3, input)")
        fruits.InsertRange(3, input)

        Console.WriteLine()
        For Each fruit As String In fruits
            Console.WriteLine(fruit)
        Next

        Console.WriteLine(vbLf & "output = fruits.GetRange(2, 3).ToArray")
        Dim output() As String = fruits.GetRange(2, 3).ToArray()

        Console.WriteLine()
        For Each fruit As String In output
            Console.WriteLine(fruit)
        Next

    End Sub
End Class

' This code example produces the following output:
'
' Capacity: 3
'
' Apple
' Banana
' Orange
'
' AddRange(fruits)
'
' Apple
' Banana
' Orange
' Apple
' Banana
' Orange
'
' RemoveRange(2, 2)
'
' Apple
' Banana
' Banana
' Orange
'
' InsertRange(3, input)
'
' Apple
' Banana
' Banana
' Mango
' Pineapple
' Watermelon
' Orange
'
' output = fruits.GetRange(2, 3).ToArray
'
' Banana
' Mango
' Pineapple

Hinweise

Die Elemente werden in die List<T> gleiche Reihenfolge kopiert, in der sie vom Enumerationselement der Auflistung gelesen werden.

Dieser Konstruktor ist ein O(n)-Vorgang, wobei n die Anzahl der Elemente in collection.

Weitere Informationen

Gilt für:

List<T>(Int32)

Quelle:
List.cs
Quelle:
List.cs
Quelle:
List.cs
Quelle:
List.cs
Quelle:
List.cs

Initialisiert eine neue Instanz der Klasse, die List<T> leer ist und über die angegebene Anfangskapazität verfügt.

public:
 List(int capacity);
public List(int capacity);
new System.Collections.Generic.List<'T> : int -> System.Collections.Generic.List<'T>
Public Sub New (capacity As Integer)

Parameter

capacity
Int32

Die Anzahl der Elemente, die die neue Liste anfänglich speichern kann.

Ausnahmen

capacity ist kleiner als 0.

Beispiele

Im folgenden Beispiel wird der List<T>(Int32) Konstruktor veranschaulicht. Eine List<T> Von Zeichenfolgen mit einer Kapazität von 4 wird erstellt, da die ultimative Größe der Liste bekannt ist, genau 4. Die Liste wird mit vier Zeichenfolgen aufgefüllt, und eine schreibgeschützte Kopie wird mithilfe der AsReadOnly Methode erstellt.

using System;
using System.Collections.Generic;

public partial class Program
{
    public static void Main()
    {
        List<string> animals = new List<string>(4);

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

        animals.Add("Cat");
        animals.Add("Dog");
        animals.Add("Squirrel");
        animals.Add("Wolf");

        Console.WriteLine();
        foreach (string animal in animals)
        {
            Console.WriteLine(animal);
        }

        Console.WriteLine("\nIList<string> roAnimals = animals.AsReadOnly()");
        IList<string> roAnimals = animals.AsReadOnly();

        Console.WriteLine("\nElements in the read-only IList:");
        foreach (string animal in roAnimals)
        {
            Console.WriteLine(animal);
        }

        Console.WriteLine("\nanimals[2] = \"Lion\"");
        animals[2] = "Lion";

        Console.WriteLine("\nElements in the read-only IList:");
        foreach (string animal in roAnimals)
        {
            Console.WriteLine(animal);
        }
    }
}

/*
    This code example produces the following output:

    Capacity: 4

    Cat
    Dog
    Squirrel
    Wolf

    IList<string> roAnimals = animals.AsReadOnly()

    Elements in the read-only IList:
    Cat
    Dog
    Squirrel
    Wolf

    animals[2] = "Lion"

    Elements in the read-only IList:
    Cat
    Dog
    Lion
    Wolf
*/
Imports System.Collections.Generic

Partial Public Class Program
    Public Shared Sub Main()

        Dim animals As New List(Of String)(4)

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

        animals.Add("Cat")
        animals.Add("Dog")
        animals.Add("Squirrel")
        animals.Add("Wolf")

        Console.WriteLine()
        For Each animal As String In animals
            Console.WriteLine(animal)
        Next

        Console.WriteLine(vbLf & _
            "Dim roAnimals As IList(Of String) = animals.AsReadOnly")
        Dim roAnimals As IList(Of String) = animals.AsReadOnly

        Console.WriteLine(vbLf & "Elements in the read-only IList:")
        For Each animal As String In roAnimals
            Console.WriteLine(animal)
        Next

        Console.WriteLine(vbLf & "animals(2) = ""Lion""")
        animals(2) = "Lion"

        Console.WriteLine(vbLf & "Elements in the read-only IList:")
        For Each animal As String In roAnimals
            Console.WriteLine(animal)
        Next

    End Sub
End Class

' This code example produces the following output:
'
' Capacity: 4
'
' Cat
' Dog
' Squirrel
' Wolf
'
' Dim roAnimals As IList(Of String) = animals.AsReadOnly
'
' Elements in the read-only IList:
' Cat
' Dog
' Squirrel
' Wolf
'
' animals(2) = "Lion"
'
' Elements in the read-only IList:
' Cat
' Dog
' Lion
' Wolf

Hinweise

Die Kapazität eines Elements List<T> ist die Anzahl der Elemente, die aufbewahrt List<T> werden können. Wenn Elemente zu einem List<T>Element hinzugefügt werden, wird die Kapazität bei Bedarf automatisch erhöht, indem das interne Array neu zugeordnet wird.

Wenn die Größe der Auflistung geschätzt werden kann, beseitigt die Angabe der anfänglichen Kapazität die Notwendigkeit, eine Reihe von Größenänderungsvorgängen auszuführen, während Elemente hinzugefügt werden List<T>.

Die Kapazität kann durch Aufrufen der TrimExcess Methode oder durch explizites Festlegen der Capacity Eigenschaft verringert werden. Durch verringern der Kapazität wird der Arbeitsspeicher neu zuordnen und alle Elemente in der List<T>Datei kopiert.

Dieser Konstruktor ist ein O(1)-Vorgang.

Vorsicht

Wenn capacity die Benutzereingabe erfolgt, verwenden Sie lieber den parameterlosen Konstruktor, und lassen Sie die Größe der Sammlung ändern, wenn Elemente hinzugefügt werden. Wenn Sie einen vom Benutzer angegebenen Wert verwenden müssen, setzen Sie ihn entweder auf einen angemessenen Grenzwert (z. B. ) oder stellen Sie sicher, Math.Clamp(untrustedValue, 0, 20)dass die Elementanzahl mit dem angegebenen Wert übereinstimmt.

Weitere Informationen

Gilt für: