How do I remove an object from a list?

List.Remove[T] Method

Definition  Namespace:    System.Collections.Generic  Assembly:System.Collections.dll Assembly:mscorlib.dll Assembly:netstandard.dll

Important

Some information relates to prerelease product that may be substantially modified before its released. Microsoft makes no warranties, express or implied, with respect to the information provided here.

In this article

Removes the first occurrence of a specific object from the List. public: virtual bool Remove[T item]; public bool Remove [T item]; abstract member Remove : 'T -> bool override this.Remove : 'T -> bool Public Function Remove [item As T] As Boolean

Parameters item T

The object to remove from the List. The value can be null for reference types.

Returns Boolean

true if item is successfully removed; otherwise, false.  This method also returns false if item was not found in the List.

Implements Remove[T]

Examples

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

Remarks

If type T implements the IEquatable generic interface, the equality comparer is the Equals method of that interface; otherwise, the default equality comparer is Object.Equals.

This method performs a linear search; therefore, this method is an O[n] operation, where n is Count.

Applies to

See also

  • RemoveAt[Int32]
  • RemoveRange[Int32, Int32]
  • Add[T]
  • Insert[Int32, T]
  • Performing Culture-Insensitive String Operations in Collections

Video liên quan

Chủ Đề