Home > Mobile >  C#: Sorting an array results in an InvalidOperationException
C#: Sorting an array results in an InvalidOperationException

Time:01-04

I need to sort a JsonArray of JsonObjects by a property, which results in an error:

System.InvalidOperationException: failed to compare two elements in the array.
Inner Exception: ArgumentException: t least one object must implement IComparable

This baffles me, since as far as I know all objects are of the same type.

This is my code:

    private JsonArray sortOnStartTime(JsonArray arrayToSort)
    {
        var testArray = arrayToSort.OrderBy(x => x["startTime"]); //breakpoint here
        // return (JsonArray)JsonNode.Parse(JsonSerializer.Serialize(arrayToSort.OrderBy(x => x["startTime"])));
        return new JsonArray();
    }

If I place the breakpoint, then my Locals window in Visual Studio reveals the following on arrayToSort:

enter image description here

There are 104 JsonObjects, and after stepping through x => x["startTime"], it turns out that the error occurs when the last JsonObject - which has a startTime of 0 - is encountered.

In what way does this last element differ from the 103 before? What do I have to do to get rid of the exception? I'm using .NET 6.0.

CodePudding user response:

As error says - JsonValue (and it's internal inheritor JsonValueTrimmable<>) does not implement IComparable. If you don't want to parse json into classes - then you need to extract actual value. In your case it seems something like the following should work:

var sorted = arrayToSort
    .OrderBy(x => x["startTime"]?.GetValue<double>())
    .ToList();
  • Related