5 people like it.

List Remove trick

Extension methods to List<'T> (aliased ResizeArray<'T> in F#) that provide optimised item removal for unordered lists where item order is not significant.

1: 
2: 
3: 
4: 
5: 
6: 
7: 
type System.Collections.Generic.List<'T> with
  member this.RemoveAtUnordered(index:int) =
    this.[index] <- this.[this.Count-1]
    this.RemoveAt(this.Count-1)
  member this.RemoveUnordered(item:'T) =
    let index = this.IndexOf(item)
    if index <> - 1 then this.RemoveAtUnordered(index)
namespace System
namespace System.Collections
namespace System.Collections.Generic
Multiple items
type List<'T> =
  new : unit -> List<'T> + 2 overloads
  member Add : item:'T -> unit
  member AddRange : collection:IEnumerable<'T> -> unit
  member AsReadOnly : unit -> ReadOnlyCollection<'T>
  member BinarySearch : item:'T -> int + 2 overloads
  member Capacity : int with get, set
  member Clear : unit -> unit
  member Contains : item:'T -> bool
  member ConvertAll<'TOutput> : converter:Converter<'T, 'TOutput> -> List<'TOutput>
  member CopyTo : array:'T[] -> unit + 2 overloads
  ...
  nested type Enumerator

Full name: System.Collections.Generic.List<_>

--------------------
System.Collections.Generic.List() : unit
System.Collections.Generic.List(capacity: int) : unit
System.Collections.Generic.List(collection: System.Collections.Generic.IEnumerable<'T>) : unit
val this : System.Collections.Generic.List<'T>
member System.Collections.Generic.List.RemoveAtUnordered : index:int -> unit

Full name: Script.RemoveAtUnordered
val index : int
Multiple items
val int : value:'T -> int (requires member op_Explicit)

Full name: Microsoft.FSharp.Core.Operators.int

--------------------
type int = int32

Full name: Microsoft.FSharp.Core.int

--------------------
type int<'Measure> = int

Full name: Microsoft.FSharp.Core.int<_>
property System.Collections.Generic.List.Count: int
System.Collections.Generic.List.RemoveAt(index: int) : unit
member System.Collections.Generic.List.RemoveUnordered : item:'T -> unit

Full name: Script.RemoveUnordered
val item : 'T
System.Collections.Generic.List.IndexOf(item: 'T) : int
System.Collections.Generic.List.IndexOf(item: 'T, index: int) : int
System.Collections.Generic.List.IndexOf(item: 'T, index: int, count: int) : int
member System.Collections.Generic.List.RemoveAtUnordered : index:int -> unit

More information

Link:http://fssnip.net/tT
Posted:8 years ago
Author:Phillip Trelford
Tags: list