Total F# n00b question. How do I sort a LIST data structure?
Edit: Sorry, my data structure is actually a LIST.
maybe i should add my code since just using ".sort" hasn't worked:
let getDataFromDb (db: MyDB) Id =
Query.query <@ seq {
big honking database/FLinq query
yield (sec, pm, sr, trade, tradeRec, i, pm_firm, files, lt)
} @> |> List.ofSeq
when I change the last line of code to this:
} @> |> List.ofSeq.sortBy fst I get the following:Error 1 The field, constructor or member 'sortBy' is not defined
ugh, what a pain. I'm trying this now:
|> List.ofSeq |> List.sortBy
But I'm getting this:
Error 开发者_运维百科1 Type mismatch. Expecting a (Security * RoleContributor * RoleContributor * SuggestedTrade * SuggestedTradeRecommendation * Idea * RoleContributor * SupportingUploadedFile * LargeText) list -> 'a but given a ('b -> 'c) -> 'b list -> 'b list The type '(Security * RoleContributor * RoleContributor * SuggestedTrade * SuggestedTradeRecommendation * Idea * RoleContributor * SupportingUploadedFile * LargeText) list' does not match the type ''a -> 'b'
Seq.sortBy would do that.
However sorting implies you know the key values of the full sequence at the time of sorting, so by definition you cannot use this on infinite sequences.
Edit: The equivalent for lists has the same name: List.sortBy
MSDN example:
let sortedList2 = List.sortBy (fun elem -> abs elem) [1; 4; 8; -2; 5]
printfn "%A" sortedList2
Edit 2:
From your new example it seems like you have a list of tuples. Now it depends on what item in the tuple you want to search by.
As others said, Seq.sortBy
is the way to go. If you're using FLinq to read some data from a database, then it is a good idea to include the sorting as part of the database query (enclosed in <@ .. @>
) so that the sorting is done on the SQL server:
let getDataFromDb (db: MyDB) Id =
<@ seq { big honking database/FLinq query
yield (sec, pm, sr, trade, tradeRec, i, pm_firm, files, lt)
|> Seq.sortBy (fun (_, _, _, _, _, i, _, _, _) -> i) @>
|> List.ofSeq
To make this a little nicer, you could return tuple containing key and all other elements as nested tuple e.g key, (sec, pm, ..., lt)
and then just sort using the first element:
|> Seq.sortBy (fun (k, _) -> k)
(I had some troubles using tuples with LINQ to Entities, but I believe that it should work in LINQ to SQL).
Use:
Query.query <@ ... @>
|> List.sortBy (fun (sec, _, _, _, _, _, _, _, _) -> sec)
Note that using tuples with that many elements is really bad style in F#. Use something more structured like a record type to give names to the fields and avoid confusion.
精彩评论