2

I have a long list of string values I am trying to sort in a grid. Initially, the default sort algorithm was used for the entire grid. However, I ended up having to rewrite the sorting for the grid because a few columns required special sorting and the grid does not allow custom sorting for specific columns. The column in question here did not require special sorting, so I just used CompareTo:

Public Function Compare(ByVal p1 as MyObj, ByVal p2 as MyObj) As Integer
    Return p1.Description.CompareTo(p2.Description)
End Function

Comparing the default grid sort method and the one I'm now using with CompareTo, I get the exact same results. However, the sort results from a direct database query differ (where the database results are correct according to what I think they should be).

Here are three examples of what I believe are incorrect sort results:

Example 1

Sort Result:

  1. TEST- A/A MY TEST
  2. TEST1000 A TEST
  3. TEST1000 TEST
  4. TESTR A TEST
  5. TEST-B/A MY TEST

Expected Result:

  1. TEST- A/A MY TEST
  2. TEST-B/A MY TEST
  3. TEST1000 A TEST
  4. TEST1000 TEST
  5. TESTR A TEST

Example 2

Sort Result:

  1. TEST- A TEST
  2. TEST ME
  3. TEST-#1 A
  4. TEST-#1 B

Expected Result:

  1. TEST ME
  2. TEST- A TEST
  3. TEST-#1 A
  4. TEST-#1 B

Example 3

Sort Result:

  1. LOUISE TEST 1
  2. LOUISE TEST 2
  3. LOUIS- TEST 1

Expected Result:

  1. LOUIS- TEST 1
  2. LOUISE TEST 1
  3. LOUISE TEST 2

Has anyone run across this before or have any ideas what could be going on here?

lmg
  • 43
  • 1
  • 7

1 Answers1

2

CompareTo does a case-sensitive, culture-sensitive sort, so characters like apostrophes, hyphens, etc. don't show where there would in a strict character encoding sort - which it seems you were expecting.

Consider using an overload of Compare that lets you specify the StringComparison as Ordinal

Jim O'Neil
  • 23,344
  • 7
  • 42
  • 67
  • Thanks Jim! That is exactly what I needed. I ended up doing the following: `String.CompareOrdinal(p1.Description, p2.Description)` – lmg Aug 15 '12 at 14:24