Was this page helpful?
Your feedback about this content is important. Let us know what you think.
Additional feedback?
1500 characters remaining
List.sortWith<'T> Function (F#)
Collapse the table of content
Expand the table of content

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 7, Windows Vista SP2, Windows XP SP3, Windows XP x64 SP2, Windows Server 2008 R2, Windows Server 2008 SP2, Windows Server 2003 SP2

F# Runtime

Supported in: 2.0, 4.0

Silverlight

Supported in: 3

Community Additions

ADD
Show:
© 2015 Microsoft