Expand Minimize

List.sortWith<'T> Function (F#)

Sorts the given list using the given comparison function.

Namespace/Module Path: Microsoft.FSharp.Collections.List

Assembly: FSharp.Core (in FSharp.Core.dll)

// Signature:
List.sortWith : ('T -> 'T -> int) -> 'T list -> 'T list

// Usage:
List.sortWith comparer list

comparer

Type: 'T -> 'T -> int

The function to compare the list elements.

list

Type: 'T list

The input list.

The sorted list.

This is a stable sort, that is, the original order of equal elements is preserved.

This function is named SortWith in compiled assemblies. If you are accessing the function from a language other than F#, or through reflection, use this name.

The following code shows how to use List.sortWith.

open System

let list1 = [ "<>"; "&"; "&&"; "&&&"; "<"; ">"; "|"; "||"; "|||" ]
printfn "Before sorting: "
list1 |> printfn "%A" 
let sortFunction (string1:string) (string2:string) =
    if (string1.Length > string2.Length) then
       1
    else if (string1.Length < string2.Length) then
       -1
    else
        String.Compare(string1, string2)
List.sortWith sortFunction list1
|> printfn "After sorting:\n%A"

Output

Before sorting: 
["<>"; "&"; "&&"; "&&&"; "<"; ">"; "|"; "||"; "|||"]
After sorting:
["&"; "|"; "<"; ">"; "&&"; "||"; "<>"; "&&&"; "|||"]

Windows 8, Windows 7, Windows Server 2012, Windows Server 2008 R2

F# Core Library Versions

Supported in: 2.0, 4.0, Portable

Was this page helpful?
(1500 characters remaining)
Thank you for your feedback
Show:
© 2014 Microsoft