Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.7k views
in Technique[技术] by (71.8m points)

sql order by - LINQ : Distinct and Orderby

I am trying to use LINQ (to EF) to get a DISTINCT list and then sort it. All the examples I found sort the result based on the DISTINCT value. But I want to sort it on a different field.

Example: Table with 2 fields (canvasSize and canvasLength);

var sizes = (from s in ent.competitors                         
             select s.canvasSize).Distinct().OrderBy(x => x);

All the examples I found give this type of answer. But it sorts by canvasSize whereas, I want to sort by canvasLength.

I'm stuck ... Any tips are greatly appreciated ...

Per J. Skeet > Additional info:

company  canvasSize  canvasLength

abc       8x10         8
d         8x10         8
e         10x10        10
f         10x10        10
g         40x40        40

I would like it to be distinct on canvasSize. The problem is that when sorted, it results in this order:

10x10
40x40
8x10  

I would like the same result set but sorted using canvasLength so the result is:

8x10
10x10
40x40
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I think what you're after may be something like this:

var sizes = (from s in ent.competitors                         
             select new { s.canvasSize, s.canvasLength })
            .Distinct()
            .OrderBy(x => x.canvasLength);

Update

Based on the extra information in your question, the following should do what you want:

var sizes = ent.competitors
               .Select(c => new {c.canvasSize, c.canvasLength})
               .Distinct()
               .OrderBy(x => x.canvasLength)
               .Select(x => x.CanvasSize)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...