How can I sort a list of this class where T in the list can be string and integers.
Edit: I have simplified the query code. The ToArray() method in results2 generates the error. Why is that?
var results1 = Entities.OrderBy(x => ((Cell<object>)x.RowData[CurrentPlugin.SortOrderInfo.ColumnIndex]).Value);
var results2 = Entities.OrderBy(x => ((Cell<object>)x.RowData[CurrentPlugin.SortOrderInfo.ColumnIndex]).Value).ToArray();
System.InvalidCastException: 'Unable to cast object of type 'Cell
1[System.String]' to type 'Cell
1[System.Object]'.'
public class Cell<T> : IComparable<Cell<T>>
{
public Cell()
{
Text = string.Empty;
Value = default;
}
public Cell(int index)
{
Index = index;
Text = string.Empty;
Value = default;
}
public Cell(string text)
{
Text = text;
Value = default;
}
public Cell(string text, T value)
{
Text = text;
Value = value;
}
public int Index { get; set; }
public string Text { get; set; }
public T Value { get; set; }
public int CompareTo(Cell<T>? other)
{
if (other == null)
return 1;
// Compare based on the type of the values
if (Value is IComparable<T> comparableValue)
return comparableValue.CompareTo(other.Value);
// If the Value type is not comparable, just compare the Text values
return Text.CompareTo(other.Text);
}
public override string ToString()
{
return Text;
}
}