List<T> 类
定义
重要
一些信息与预发行产品相关,相应产品在发行之前可能会进行重大修改。 对于此处提供的信息,Microsoft 不作任何明示或暗示的担保。
表示可通过索引访问的对象的强类型列表。 提供用于对列表进行搜索、排序和操作的方法。
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
generic <typename T>
public ref class List : System::Collections::Generic::ICollection<T>, System::Collections::Generic::IEnumerable<T>, System::Collections::Generic::IList<T>, System::Collections::IList
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
[System.Serializable]
public class List<T> : System.Collections.Generic.ICollection<T>, System.Collections.Generic.IEnumerable<T>, System.Collections.Generic.IList<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 ICollection<'T>
interface seq<'T>
interface IEnumerable
interface IList<'T>
interface IReadOnlyCollection<'T>
interface IReadOnlyList<'T>
interface ICollection
interface IList
[<System.Serializable>]
type List<'T> = class
interface IList<'T>
interface ICollection<'T>
interface seq<'T>
interface IList
interface ICollection
interface IEnumerable
[<System.Serializable>]
type List<'T> = class
interface IList<'T>
interface ICollection<'T>
interface IList
interface ICollection
interface IReadOnlyList<'T>
interface IReadOnlyCollection<'T>
interface seq<'T>
interface IEnumerable
[<System.Serializable>]
type List<'T> = class
interface IList<'T>
interface ICollection<'T>
interface seq<'T>
interface IEnumerable
interface IList
interface ICollection
interface IReadOnlyList<'T>
interface IReadOnlyCollection<'T>
type List<'T> = class
interface IList<'T>
interface ICollection<'T>
interface IReadOnlyList<'T>
interface IReadOnlyCollection<'T>
interface seq<'T>
interface IList
interface ICollection
interface IEnumerable
[<System.Serializable>]
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)
Public Class List(Of T)
Implements ICollection(Of T), IEnumerable(Of T), IList, IList(Of T)
类型参数
- T
列表中元素的类型。
- 继承
-
List<T>
- 派生
- 属性
- 实现
示例
以下示例演示如何在一个 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
以下示例演示类型字符串泛型类的 List<T> 多个属性和方法。 (有关复杂类型的示例 List<T> ,请参阅 Contains method.)
无参数构造函数用于创建具有默认容量的字符串列表。 将显示该 Capacity 属性,然后使用 Add 该方法添加多个项。 列出项,并 Capacity 再次显示该属性以及 Count 该属性,以显示容量已根据需要增加。
该方法 Contains 用于测试列表中某个项的存在, Insert 该方法用于在列表中间插入新项,并再次显示列表的内容。
默认 Item[] 属性 (C#) 中的索引器用于检索项, Remove 该方法用于删除前面添加的重复项的第一个实例,并再次显示内容。 该方法 Remove 始终删除它遇到的第一个实例。
该方法 TrimExcess 用于减少容量以匹配计数,并 Capacity 显示属性 Count 。 如果未使用的容量小于总容量的 10%,则列表不会调整大小。
最后, Clear 该方法用于从列表中删除所有项,并 Capacity 显示属性 Count 。
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
*)
注解
该 List<T> 类是类 ArrayList 的泛型等效项。 它通过使用一个数组实现 IList<T> 泛型接口,该数组的大小根据需要动态增加。
可以使用或AddRange方法将项添加到 a。List<T> Add
该 List<T> 类使用相等比较器和排序比较器。
方法(例如 Contains, IndexOf) LastIndexOf对 Remove 列表元素使用相等比较器。 类型
T
的默认相等比较器按如下所示确定。 如果类型T
实现 IEquatable<T> 泛型接口,则相等比较器是 Equals(T) 该接口的方法;否则,默认相等比较器为 Object.Equals(Object)。用于列表元素的排序比较器等BinarySearchSort方法。 类型
T
的默认比较器按如下所示确定。 如果类型T
实现 IComparable<T> 泛型接口,则默认比较器是 CompareTo(T) 该接口的方法;否则,如果类型T
实现非泛型 IComparable 接口,则默认比较器是 CompareTo(Object) 该接口的方法。 如果类型T
实现两个接口,则没有默认比较器,并且必须显式提供比较器或比较委托。
List<T>不能保证排序。 必须先对 (执行操作进行排序 List<T> ,例如 BinarySearch 需要 List<T> 排序的) 。
可以使用整数索引访问此集合中的元素。 此集合中的索引从零开始。
仅.NET Framework: 对于非常大List<T>的对象,可以通过将配置元素的属性 <gcAllowVeryLargeObjects>
设置为enabled``true
运行时环境中,将 64 位系统上的最大容量增加到 20 亿个元素。
List<T> 接受 null
作为引用类型的有效值,并允许重复元素。
有关类的 List<T> 不可变版本,请参阅 ImmutableList<T>。
性能注意事项
在决定是否使用 List<T> 具有类似功能的两 ArrayList 个类时,请记住 List<T> ,该类在大多数情况下表现更好,并且类型安全。 如果引用类型用于类的类型T
List<T>,则两个类的行为相同。 但是,如果值类型用于类型 T
,则需要考虑实现和装箱问题。
如果值类型用于类型 T
,编译器将生成特定于该值类型的类的 List<T> 实现。 这意味着,在使用元素之前不必装箱对象的列表元素,在创建大约 500 个列表元素之后,不装箱列表元素保存的 List<T> 内存大于用于生成类实现的内存。
确保用于类型 T
的值类型实现 IEquatable<T> 泛型接口。 否则,例如 Contains ,方法必须调用 Object.Equals(Object) 该方法,该方法将受影响的列表元素装箱。 如果值类型实现 IComparable 接口,并且你拥有源代码,还实现 IComparable<T> 泛型接口,以防止 BinarySearch 和 Sort 方法将列表元素装箱。 如果你不拥有源代码,请将对象 IComparer<T> 传递给 BinarySearch 和 Sort 方法
使用类的特定于类型的实现 List<T> ,而不是使用 ArrayList 类或自行编写强类型包装器集合是有好处的。 这是因为你的实现必须为你执行.NET Framework的作用,公共语言运行时可以共享 Microsoft 中间语言代码和元数据,而你的实现不能这样做。
F# 注意事项
该 List<T> 类在 F# 代码中不经常使用。 相反, 通常首选不可变、单向链接的列表。 F# List
提供有序且不可变的一系列值,并且支持在功能样式开发中使用。 从 F# 使用时, List<T> 该类通常由 ResizeArray<'T>
类型缩写引用,以避免与 F# 列表的命名冲突。
构造函数
List<T>() |
初始化 List<T> 类的新实例,该实例为空并且具有默认初始容量。 |
List<T>(IEnumerable<T>) |
初始化 List<T> 类的新实例,该实例包含从指定集合复制的元素并且具有足够的容量来容纳所复制的元素。 |
List<T>(Int32) |
初始化 List<T> 类的新实例,该实例为空并且具有指定的初始容量。 |
属性
Capacity |
获取或设置该内部数据结构在不调整大小的情况下能够容纳的元素总数。 |
Count |
获取 List<T> 中包含的元素数。 |
Item[Int32] |
获取或设置指定索引处的元素。 |
方法
Add(T) |
将对象添加到 List<T> 的结尾处。 |
AddRange(IEnumerable<T>) |
将指定集合的元素添加到 List<T> 的末尾。 |
AsReadOnly() |
返回当前集合的只读 ReadOnlyCollection<T> 包装器。 |
BinarySearch(Int32, Int32, T, IComparer<T>) |
使用指定的比较器在已排序 List<T> 的某个元素范围中搜索元素,并返回该元素从零开始的索引。 |
BinarySearch(T) |
使用默认的比较器在整个已排序的 List<T> 中搜索元素,并返回该元素从零开始的索引。 |
BinarySearch(T, IComparer<T>) |
使用指定的比较器在整个已排序的 List<T> 中搜索元素,并返回该元素从零开始的索引。 |
Clear() |
从 List<T> 中移除所有元素。 |
Contains(T) |
确定某元素是否在 List<T> 中。 |
ConvertAll<TOutput>(Converter<T,TOutput>) |
将当前 List<T> 中的元素转换为另一种类型,并返回包含已转换元素的列表。 |
CopyTo(Int32, T[], Int32, Int32) |
从目标数组的指定索引处开始,将元素的范围从 List<T> 复制到兼容的一维数组。 |
CopyTo(T[]) |
从目标数组的开头开始,将整个 List<T> 复制到兼容的一维数组。 |
CopyTo(T[], Int32) |
从目标数组的指定索引处开始,将整个 List<T> 复制到兼容的一维数组。 |
EnsureCapacity(Int32) |
确保此列表的容量至少是指定的 |
Equals(Object) |
确定指定对象是否等于当前对象。 (继承自 Object) |
Exists(Predicate<T>) |
确定 List<T> 是否包含与指定谓词定义的条件匹配的元素。 |
Find(Predicate<T>) |
搜索与指定谓词所定义的条件相匹配的元素,并返回整个 List<T> 中的第一个匹配元素。 |
FindAll(Predicate<T>) |
检索与指定谓词定义的条件匹配的所有元素。 |
FindIndex(Int32, Int32, Predicate<T>) |
搜索与指定谓词所定义的条件相匹配的一个元素,并返回 List<T> 中从指定的索引开始、包含指定元素个数的元素范围内第一个匹配项的从零开始的索引。 |
FindIndex(Int32, Predicate<T>) |
搜索与指定谓词所定义的条件相匹配的元素,并返回 List<T> 中从指定索引到最后一个元素的元素范围内第一个匹配项的从零开始的索引。 |
FindIndex(Predicate<T>) |
搜索与指定谓词所定义的条件相匹配的元素,并返回整个 List<T> 中第一个匹配元素的从零开始的索引。 |
FindLast(Predicate<T>) |
搜索与指定谓词所定义的条件相匹配的元素,并返回整个 List<T> 中的最后一个匹配元素。 |
FindLastIndex(Int32, Int32, Predicate<T>) |
搜索与指定谓词所定义的条件相匹配的元素,并返回 List<T> 中包含指定元素个数、到指定索引结束的元素范围内最后一个匹配项的从零开始的索引。 |
FindLastIndex(Int32, Predicate<T>) |
搜索与由指定谓词定义的条件相匹配的元素,并返回 List<T> 中从第一个元素到指定索引的元素范围内最后一个匹配项的从零开始的索引。 |
FindLastIndex(Predicate<T>) |
搜索与指定谓词所定义的条件相匹配的元素,并返回整个 List<T> 中最后一个匹配元素的从零开始的索引。 |
ForEach(Action<T>) |
对 List<T> 的每个元素执行指定操作。 |
GetEnumerator() |
返回循环访问 List<T> 的枚举数。 |
GetHashCode() |
作为默认哈希函数。 (继承自 Object) |
GetRange(Int32, Int32) |
在源 List<T> 中创建元素范围的浅表复制。 |
GetType() |
获取当前实例的 Type。 (继承自 Object) |
IndexOf(T) |
搜索指定的对象,并返回整个 List<T> 中第一个匹配项的从零开始的索引。 |
IndexOf(T, Int32) |
搜索指定对象并返回 List<T> 中从指定索引到最后一个元素这部分元素中第一个匹配项的从零开始索引。 |
IndexOf(T, Int32, Int32) |
搜索指定对象并返回 List<T> 中从指定索引开始并包含指定元素数的这部分元素中第一个匹配项的从零开始索引。 |
Insert(Int32, T) |
将元素插入 List<T> 的指定索引处。 |
InsertRange(Int32, IEnumerable<T>) |
将集合中的元素插入 List<T> 的指定索引处。 |
LastIndexOf(T) |
搜索指定对象并返回整个 List<T> 中最后一个匹配项的从零开始索引。 |
LastIndexOf(T, Int32) |
搜索指定对象并返回 List<T> 中从第一个元素到指定索引这部分元素中最后一个匹配项的从零开始的索引。 |
LastIndexOf(T, Int32, Int32) |
搜索指定对象并返回 List<T> 中到指定索引为止包含指定元素数的这部分元素中最后一个匹配项的从零开始索引。 |
MemberwiseClone() |
创建当前 Object 的浅表副本。 (继承自 Object) |
Remove(T) |
从 List<T> 中移除特定对象的第一个匹配项。 |
RemoveAll(Predicate<T>) |
移除与指定的谓词所定义的条件相匹配的所有元素。 |
RemoveAt(Int32) |
移除 List<T> 的指定索引处的元素。 |
RemoveRange(Int32, Int32) |
从 List<T> 中移除一系列元素。 |
Reverse() |
将整个 List<T> 中元素的顺序反转。 |
Reverse(Int32, Int32) |
将指定范围中元素的顺序反转。 |
Sort() |
使用默认比较器对整个 List<T> 中的元素进行排序。 |
Sort(Comparison<T>) |
使用指定的 Comparison<T>,对整个 List<T> 中的元素进行排序。 |
Sort(IComparer<T>) |
使用指定的比较器对整个 List<T> 中的元素进行排序。 |
Sort(Int32, Int32, IComparer<T>) |
使用指定的比较器对 List<T> 中某个范围内的元素进行排序。 |
ToArray() |
将 List<T> 的元素复制到新数组中。 |
ToString() |
返回表示当前对象的字符串。 (继承自 Object) |
TrimExcess() |
将容量设置为 List<T> 中元素的实际数目(如果该数目小于某个阈值)。 |
TrueForAll(Predicate<T>) |
确定 List<T> 中的每个元素是否都与指定谓词定义的条件匹配。 |
显式接口实现
ICollection.CopyTo(Array, Int32) |
从特定的 ICollection 索引开始,将 Array 的元素复制到一个 Array 中。 |
ICollection.IsSynchronized |
获取一个值,该值指示是否同步对 ICollection 的访问(线程安全)。 |
ICollection.SyncRoot |
获取可用于同步对 ICollection 的访问的对象。 |
ICollection<T>.IsReadOnly |
获取一个值,该值指示 ICollection<T> 是否为只读。 |
IEnumerable.GetEnumerator() |
返回循环访问集合的枚举数。 |
IEnumerable<T>.GetEnumerator() |
返回循环访问集合的枚举数。 |
IList.Add(Object) |
将某项添加到 IList 中。 |
IList.Contains(Object) |
确定 IList 是否包含特定值。 |
IList.IndexOf(Object) |
确定 IList 中特定项的索引。 |
IList.Insert(Int32, Object) |
在 IList 中的指定索引处插入一个项。 |
IList.IsFixedSize |
获取一个值,该值指示 IList 是否具有固定大小。 |
IList.IsReadOnly |
获取一个值,该值指示 IList 是否为只读。 |
IList.Item[Int32] |
获取或设置指定索引处的元素。 |
IList.Remove(Object) |
从 IList 中移除特定对象的第一个匹配项。 |
扩展方法
适用于
线程安全性
此类型的Visual Basic) 成员中的公共静态 (Shared
是线程安全的。 但不保证所有实例成员都是线程安全的。
可以安全地对某个 List<T>集合执行多个读取操作,但如果正在读取集合时修改集合,则可能会出现问题。 若要确保线程安全,请在读取或写入操作期间锁定集合。 若要允许多个线程访问集合以读取和写入,必须实现自己的同步。 有关具有内置同步的集合,请参阅命名空间中的 System.Collections.Concurrent 类。 有关固有线程安全的替代方法,请参阅 ImmutableList<T> 该类。