Object.CompareTo(Object) for unknown data type
Asked Answered
R

3

5

I am trying to compare objects in an object[] that are of a single type (unknown at runtime). They are of System.string, int, decimal, Datetime, or bool types.

Is there a way to compare two of these objects to determine if one is greater or less than another without having to cast them into their appropriate type first?

Roadstead answered 22/11, 2011 at 20:46 Comment(1)
You have at least to cast them to IComparable and then use CompareTo .Reisinger
G
7

The types in question all implement IComparable, so, if being able to compare elements is an intrinsic requirement of your array, you could declare it as an IComparable[] instead.

Gametophyte answered 22/11, 2011 at 20:51 Comment(1)
Hah, You were 3 seconds faster ;-)Regenerator
G
2

All of those types implement IComparable interface, so you can cast your objects to IComparable (or just keep an IComparable[] array instead of object[]). Then you can use CompareTo(object x) method.

Gunthar answered 22/11, 2011 at 20:51 Comment(0)
D
1

All of the types you mention implements 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));
Delaine answered 22/11, 2011 at 20:51 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.