How to sort a list of different type objects by timestamp

246 views Asked by At

New to F# Have a list of objects. Objects share the same base class, but the timestamp attribute we want to order by is not present on the base class. Every object in the list will have the timestamp attribute.

Requirement is to order the objects by the timestamp descending.

Attempted

let sortedList = unsortedList.Sort();

This results in

System.InvalidOperationException: Failed to compare two elements in the array. ---> System.ArgumentException: At least one object must implement IComparable. at System.Collections.Comparer.Compare(Object a, Object b)

2

There are 2 answers

1
Gus On BEST ANSWER

You didn't post code so I can't give you the exact code to solve it.

Typically you will have a property in the Base Class or alternatively in an Interface, but let's suppose you have this:

type A() = class end

type B(x) =
    inherit A()
    member val timestamp = x with get, set

type C(x) =
    inherit A()
    member val timestamp = x with get, set

let lst = [ new B(5) :> A ; new C(15) :> A; new B(4) :> A ;]

And you can't touch that code. Then what you can do is this:

let getTimeStamp (x:A) = 
    match x with
    | :? B as x -> x.timestamp 
    | :? C as x -> x.timestamp 
    | _ -> failwith "subtype not handled"

lst |> List.sortBy (fun x -> -getTimeStamp x)

Using reflection is another possibility (see Mau's answer).

If you post a code sample I can give you a more specific solution and test it.

0
Mau On

You can access the timestamp property using the dynamic operator ? as shown here:

C#'s 'dynamic' in F#