Search code examples
sdkdynamics-crmmicrosoft-dynamicsguidquery-expressions

Dynamics CRM OrderBy expression not working


I am trying to download Lead IDs from Dynamics CRM and I need them ordered by the LeadId :

    IOrganizationService orgService = dynamicService.OrgService;
    QueryExpression request = new QueryExpression()
    {
        EntityName = "lead",
        ColumnSet = new ColumnSet("leadid"),
        Criteria = new FilterExpression(),
        PageInfo = new PagingInfo() { ReturnTotalRecordCount = true, Count = 50, PageNumber = 1 }
    };
    request.Orders.Add(new OrderExpression("leadid", OrderType.Ascending));

    EntityCollection response = orgService.RetrieveMultiple(request);
    foreach(Entity e in response.Entities)
    {
        Console.WriteLine($"{e.Attributes["leadid"]}");
    }

However, this is returning them in random order.

b9b0f003-356d-e911-a966-000d3a1d7430
4298cdf4-4370-e911-a966-000d3a1d7430
97582b3c-2f6d-e911-a971-000d3a1d7b43
92d57a83-338f-e611-80e0-c4346bb588e8
a0d57a83-338f-e611-80e0-c4346bb588e8
a2d57a83-338f-e611-80e0-c4346bb588e8
a6d57a83-338f-e611-80e0-c4346bb588e8

What am I doing wrong here?


Solution

  • This is correctly sorted per GUID sort algorithm.

    The comparison is made by looking at byte "groups" right-to-left, and left-to-right within a byte "group". A byte group is what is delimited by the '-' character. More technically, we look at bytes {10 to 15} first, then {8-9}, then {6-7}, then {4-5}, and lastly {0 to 3}.

    So b9b0f003-356d-e911-a966-000d3a1d7430 is smaller than 4298cdf4-4370-e911-a966-000d3a1d7430.

    Similarly 4298cdf4-4370-e911-a966-000d3a1d7430 is smaller than 97582b3c-2f6d-e911-a971-000d3a1d7b43.

    And so on.