Reputation: 5075
I am working on .NET CORE 2.0 application and part of that I am require sort GUID in descending order. I have list of GUID in List pass to another method where this collection is sorted in descending order but I have found result is different then use IQueryable Linq as select(x=>x.id).OrderByDescending(x=>x)
also comparing with SQL Server, the second option seems correct.
I need List sort in descending order output as same result as IQueryable Linq as select(x=>x.id).OrderByDescending(x=>x)
List<Guid> sortedList =
C95F4897-35D8-409D-BF0E-B0D6E1BCAC55
D867FD57-F728-46E9-BFF0-F168BAC674C4
F05BCAA7-600E-406F-B9F3-7CD839FFC98B
383525C6-F158-431C-A6A5-B42FF3CBF5AE
I have also tried following code but not getting correct result
var s1 = sortedList.OrderByDescending(i => i);
sortedList.Sort();
sortedList.Reverse();
Upvotes: 2
Views: 1059
Reputation: 15140
When you call .OrderByDescending on a list, you are calling Enumerable.OrderByDescending. Conversely, when you are calling .OrderByDescending on a linq query, you are calling Queryable.OrderByDescending.
The difference (the difference that matters here) is the enumerable method uses the default comparer (in this case of datatype GUID
), while the queryable method is converted to a sql statement which is executed on the database, hence using the SQL comparer (of uniqueidentifier
). The GUID
comparer uses all 16 bytes equally, while in SQL the last 6 bytes are the most significant (Source1, Source2(old, but still valid)).
You say you desire the result of the queryable method, while using the enumerable method (in essence). You can achieve this by using the System.Data.SqlTypes.SqlGuid
datatype instead of system.Guid
. You can simply cast your Guid's to SqlGuid's. Alternatively, and probably a much cleaner solution, you can create your own comparer using SqlGuid.CompareTo
method, and use that in the order by: OrderByDescending(x => x, new MyComparer())
.
Upvotes: 4