I want to OrderBy a field using Linq and SQLite. Table:
| OriginalWord |
|---|
| Test1 |
| eat |
| test2 |
I want to order by OriginalWord:
await Database.Table<Word>()
.Where(i => i.DictionaryId == id)
.OrderBy(w => w.OriginalWord)
.ToListAsync();
Order in SQLite is case sensitive. I found a solution:
internal sealed class NameComparer : IComparer<string> {
private static readonly NameComparer DefaultInstance = new NameComparer();
static NameComparer() { }
private NameComparer() { }
public static NameComparer Default {
get { return DefaultInstance; }
}
public int Compare(string x, string y) {
int length = Math.Min(x.Length, y.Length);
for (int i = 0; i < length; ++i) {
if (x[i] == y[i]) continue;
if (x[i] == '-') return 1;
if (y[i] == '-') return -1;
return x[i].CompareTo(y[i]);
}
return x.Length - y.Length;
}
}
var sorted = names.OrderBy(name => name, NameComparer.Default).ToList();
This is not working because OrderByhas has only 1 parameter:
I'm using NET7 (MAUI) and SQLite.

The problem is that databases may use an index to do sorting efficiently. But this index may be case sensitive, and may follow some other rules regarding ordering of strings. This is called Collation, and you should be able to specify this in your database, either for the entire database, or for specific columns.
So if you want your query to run efficiently in the database you likely need to change the collation.
A workaround is to just load the unsorted list into memory, and sort it in memory instead. This will have some performance penalty since no index can be used. But sorting is fairly efficient, so I would expect it to be fast enough: