Partager via


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

Parameters

  • comparer
    Type: 'T -> 'T ->int

    The function to compare the list elements.

  • list
    Type: 'Tlist

    The input list.

Return Value

The sorted list.

Remarks

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.

Example

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:
["&"; "|"; "<"; ">"; "&&"; "||"; "<>"; "&&&"; "|||"]

Platforms

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

Version Information

F# Core Library Versions

Supported in: 2.0, 4.0, Portable

See Also

Reference

Collections.List Module (F#)

Microsoft.FSharp.Collections Namespace (F#)