Object.CompareTo (Object) for an unknown data type

I am trying to compare objects in object[]which are of the same type (unknown at runtime). They are of types System.string, int, decimal, Datetimeor bool.

Is there a way to compare two of these objects to determine if it is larger or smaller than the other without first inserting their corresponding type?

+5
source share
3 answers

All types implement IComparable, so if being able to compare items is an integral requirement of your array, you can declare it as IComparable[].

+7
source

IComparable, IComparable ( IComparable[] object[]). CompareTo(object x).

+2

All of these types implement IComparable, so you can use IComparable.CompareTo. As an example:

object[] ints = new object[] { 2, 1, 3};
object n = 2;
var compareResults = ints.OfType<IComparable>().Select(c => c.CompareTo(n));
+1
source

All Articles