Consider the following criteria query:
var x = SomeCriteria.AddOrder(new Order("Name", true)).List();
This will order the result set by the Name property, but case sensitive:
"A1"
"B1"
"a2"
Any ideas how to add the order case insensitive so result "a2" will end up before "B1"?
NHibernate supports collections implemented by System.Collections.Generic.SortedList<T> and System.Collections.Generic.SortedSet<T>. You must specify a comparer in the mapping file: Allowed values of the sort attribute are unsorted , natural and the name of a class implementing System.Collections.Generic.IComparer<T> .
Let’s say your list is having the following elements − Therefore, case sensitive order means, capital and small letters will be considered irrespective of case. The output would be − The following is our array −
The Arrays.sort (arr, Collator.getInstance ()) method is used to sort the array in a case-insensitive order. Then the sorted array is displayed.
2. Sorting With HQL Sorting with Hibernate's HQL is as simple as adding the Order By clause to the HQL query string: After this code is executed, Hibernate will generate the following SQL query: The default sort order direction is ascending. This is why the order condition, asc, is not included in the generated SQL query.
You should be able to accomplish this by ordering on a projection that normalizes the case for you. For example, Oracle has a "lower" function that will lower case string data types like varchar2 and nvarchar2; so I will use this sql function to form a projection that will order appropriately.
var projection = Projections.SqlFunction("lower", NHibernateUtil.String, Projections.Property("Name")); var x = SomeCriteria.AddOrder(Orders.Asc(projection)).List()
If you're using SQL Server, I'd recommend using the "upper" function instead of "lower" for efficiency. Microsoft has optimized its native code for performing uppercase comparisons, where the rest of the world seems to have optimized on lowercase.
Hibernate (Java) has an "ignoreCase()" method on the "Order" class, but it looks like NHibernate does not have this method on its "Order."
This is how I was thinking you could do it:
var x = SomeCriteria.AddOrder(new Order("Name", true).IgnoreCase()).List();
But unfortunately, there is no IgnoreCase().
As a workaround, you could use an HQL or SQL query - either of those should allow you to order case-insensitive.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With