Is a list a collection?

generic public ref class List : System::Collections::Generic::ICollection, System::Collections::Generic::IEnumerable, System::Collections::Generic::IList, System::Collections::Generic::IReadOnlyCollection, System::Collections::Generic::IReadOnlyList, System::Collections::IList generic public ref class List : System::Collections::Generic::ICollection, System::Collections::Generic::IEnumerable, System::Collections::Generic::IList, System::Collections::IList public class List : System.Collections.Generic.ICollection, System.Collections.Generic.IEnumerable, System.Collections.Generic.IList, System.Collections.Generic.IReadOnlyCollection, System.Collections.Generic.IReadOnlyList, System.Collections.IList [System.Serializable] public class List : System.Collections.Generic.ICollection, System.Collections.Generic.IEnumerable, System.Collections.Generic.IList, System.Collections.IList [System.Serializable] public class List : System.Collections.Generic.ICollection, System.Collections.Generic.IEnumerable, System.Collections.Generic.IList, System.Collections.Generic.IReadOnlyCollection, System.Collections.Generic.IReadOnlyList, System.Collections.IList type List interface seq interface IReadOnlyCollection interface ICollection interface IList [] type List interface ICollection interface IList interface ICollection interface IEnumerable [] type List interface ICollection interface IReadOnlyCollection interface IEnumerable [] type List interface ICollection interface IEnumerable interface IList interface ICollection interface IReadOnlyList type List interface ICollection interface IReadOnlyCollection interface IList interface ICollection interface IEnumerable [] type List interface IList interface IReadOnlyList interface seq 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] Inheritance Derived

System.Data.Services.ExpandSegmentCollection

System.Workflow.Activities.OperationParameterInfoCollection

System.Workflow.Activities.WorkflowRoleCollection

System.Workflow.ComponentModel.ActivityCollection

System.Workflow.ComponentModel.Design.ActivityDesignerGlyphCollection

Attributes

SerializableAttribute

Implements

ICollection IEnumerable IList IReadOnlyCollection IReadOnlyList ICollection IEnumerable IList

The following example demonstrates how to add, remove, and insert a simple business object in a List.

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 { 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 parts = new List[]; // 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. [] 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 [] let main argv = // We refer to System.Collections.Generic.List to avoid conflicts with the F# List module. // Note: In F# code, F# linked lists are usually preferred over // ResizeArray by its type // abbreviation ResizeArray 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 *]

The List class is the generic equivalent of the ArrayList class. It implements the IList generic interface by using an array whose size is dynamically increased as required.

You can add items to a List by using the Add or AddRange methods.

The List class uses both an equality comparer and an ordering comparer.

  • Methods such as Contains, IndexOf, LastIndexOf, and Remove use an equality comparer for the list elements. The default equality comparer for type T is determined as follows. If type T implements the IEquatable generic interface, then the equality comparer is the Equals[T] method of that interface; otherwise, the default equality comparer is Object.Equals[Object].

  • Methods such as BinarySearch and Sort use an ordering comparer for the list elements. The default comparer for type T is determined as follows. If type T implements the IComparable 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. If type T implements neither interface, then there is no default comparer, and a comparer or comparison delegate must be provided explicitly.

The List is not guaranteed to be sorted. You must sort the List before performing operations [such as BinarySearch] that require the List to be sorted.

Elements in this collection can be accessed using an integer index. Indexes in this collection are zero-based.

.NET Framework only: For very large List objects, you can increase the maximum capacity to 2 billion elements on a 64-bit system by setting the enabled attribute of the configuration element to true in the run-time environment.

List accepts null as a valid value for reference types and allows duplicate elements.

For an immutable version of the List class, see ImmutableList.

In deciding whether to use the List or ArrayList class, both of which have similar functionality, remember that the List class performs better in most cases and is type safe. If a reference type is used for type T of the List class, the behavior of the two classes is identical. However, if a value type is used for type T, you need to consider implementation and boxing issues.

If a value type is used for type T, the compiler generates an implementation of the List class specifically for that value type. That means a list element of a List object does not have to be boxed before the element can be used, and after about 500 list elements are created, the memory saved by not boxing list elements is greater than the memory used to generate the class implementation.

Make certain the value type used for type T implements the IEquatable generic interface. If not, methods such as Contains must call the Object.Equals[Object] method, which boxes the affected list element. If the value type implements the IComparable interface and you own the source code, also implement the IComparable generic interface to prevent the BinarySearch and Sort methods from boxing list elements. If you do not own the source code, pass an IComparer object to the BinarySearch and Sort methods

It is to your advantage to use the type-specific implementation of the List class instead of using the ArrayList class or writing a strongly typed wrapper collection yourself. That's because 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.

The List class is used infrequently in F# code. Instead, Lists, which are immutable, singly-linked lists, are typically preferred. An F# List provides an ordered, immutable series of values, and is supported for use in functional-style development. When used from F#, the List class is typically referred to by the ResizeArray

Chủ Đề