开发者

LINQ-to-SQL orderby question

I have a LINQ-to-SQL query, and I order on an nvarc开发者_开发问答har field called CustomerReference. The problem is, reference's that start with a capital letter seem to be after ones without capitals, when I need this the other way around. For example, if I have the following rows:

d93838
D98484

It is currently ordered in that sequence right now, however I need it reversed - so it'd be like this

D98484
d93838

Any ideas guys? Thanks


This assumes the Format [A-Za-z]\d+ and will put b3432 before C1234 but after B9999

list.OrderBy (l => l.CustomerReference.Substring(0,1).ToLower())
    .ThenByDescending(l =>l.CustomerReference.Substring(0,1).ToUpper()==l.CustomerReference.Substring(0,1))
    .ThenBy (l =>l.CustomerReference )

EDIT: I was asked for the SQL too so this is what LINQPad does

-- Region Parameters
DECLARE @p0 Int SET @p0 = 0
DECLARE @p1 Int SET @p1 = 1
DECLARE @p2 Int SET @p2 = 0
DECLARE @p3 Int SET @p3 = 1
DECLARE @p4 Int SET @p4 = 0
DECLARE @p5 Int SET @p5 = 1
-- EndRegion
SELECT [T0].CustomerReference FROM [dbo].[test] AS [t0]
ORDER BY LOWER(SUBSTRING([t0].[CustomerReference], @p0 + 1, @p1)), 
(CASE 
    WHEN UPPER(SUBSTRING([t0].[CustomerReference], @p2 + 1, @p3)) = SUBSTRING([t0].[CustomerReference], @p4 + 1, @p5) THEN 1
    WHEN NOT (UPPER(SUBSTRING([t0].[CustomerReference], @p2 + 1, @p3)) = SUBSTRING([t0].[CustomerReference], @p4 + 1, @p5)) THEN 0
    ELSE NULL
 END) DESC, [t0].[CustomerReference]


In most implementations, lower-case comes first (not least, that is how code-points are arranged ordinally). You won't be able to get SQL server to change that, so the next best thing is to bring it back unsorted, and write a custom comparer. Note that the inbuilt .NET comparers will also treat lower-case as either first or equal (compared to their upper-case equivalent), depending on the comparer.

However! Unless you limit yourself to very simple examples (ASCII etc), ordering "alike" characters is a very non-trivial exercise. Even if we ignore the Turkish I / İ / ı / i, accented characters are going to cause you problems).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜