简体   繁体   中英

Sorting a list of strings in C# to the same order as SQLite

Does anyone know how I can sort a list of strings in C# to exactly the same order that would be returned by a SQLite query - including for all special characters. I need to perform a binary search on the returned data, however my IComparer is using C#'s String's CompareOrdinal, and therefore doesn't work, as the sort order between the two is different.

I have defined the SQlite table's column as "collate nocase".

To rephrase the question, how can you sort a list of strings ignoring case?

The StringComparer class provides comparers that support a specific culture and can optionally ignore case. To sort using your thread's current culture you can use the CurrentCultureIgnoreCase comparer:

var myList=new List<string>{"aa2","Aa1"};
myList.Sort(StringComparer.CurrentCultureIgnoreCase);

The InvariantCultureIgnoreCase or OrdinalIgnoreCase comparers use invariant and ordinal comparisons respectively.

SQLite by default uses BINARY collation which is equivalent to Ordinal (paragraph 6.1 from DataTypes in SQLite v3 :

Every column of every table has an associated collating function. If no collating function is explicitly defined, then the collating function defaults to BINARY

Unless, you have changed the collation of the tables, you can use OrdinalIgnoreCase to sort in the same order ignoring case.

You can also create a comparer for a specific culture with the StringComparer.Create method.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM