I have a DataGridView and I need to use a custom sorter (derived from System.Collections.IComparer). That was working fine, but I noticed that I hadn’t quite gotten my comparisons right because it ends up doing a string compare on the cells regardless of their underlying data type. (so, 1, 10, 2) instead of (1, 2, 10).
How can I write a compare function that could appropriately compare columns regardless of their data type?
public int compare(object x, object y)
{
DataGridViewRow dr1 = (DataGridViewRow)x;
DataGridViewRow dr2 = (DataGridViewRow)y;
object cell1 = dr1.Cells["SomeName"].Value;
object cell2 = dr2.Cells["SomeName"].Value;
//Compare cell1 and cell 2 based on the data type in
//dr1.Cells["SomeName"].ValueType.
}
It seems that there a couple of essential parts to any solution to this problem.
Here are some ideas to get you started. I’ve omitted some error checking in the interest of clarity.
Assume:
Then see if you can coerce one value to the other’s type:
Now that you have instances of like type, you need to find a way to compare them.
If you are using C# 4, then the dynamic keyword may be your friend:
If you aren’t using C# 4, you can see if the values implement
IComparable:Or perhaps it implements a generic
IComparable<T>, in which case may need to resort to some reflection trickery:Finally, you can see if
Comparer<T>.Defaultwill work, again using some reflection:If none of these work, then you will have to fallback to string comparison.