LINQ:区分和排序 [英] LINQ : Distinct and Orderby
问题描述
我正在尝试使用LINQ(到EF)来获取DISTINCT列表,然后对其进行排序.我发现的所有示例均基于DISTINCT值对结果进行排序.但我想在另一个字段上对它进行排序.
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.
示例:具有2个字段(canvasSize和canvasLength)的表;
Example: Table with 2 fields (canvasSize and canvasLength);
var sizes = (from s in ent.competitors
select s.canvasSize).Distinct().OrderBy(x => x);
我发现的所有示例都给出了这种类型的答案.但是它是按canvasSize排序的,而我想按canvasLength排序.
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>其他信息:
Per J. Skeet > Additional info:
company canvasSize canvasLength
abc 8x10 8
d 8x10 8
e 10x10 10
f 10x10 10
g 40x40 40
我希望在canvasSize上与众不同.问题在于,排序时,其结果顺序如下:
I would like it to be distinct on canvasSize. The problem is that when sorted, it results in this order:
10x10
40x40
8x10
我想要相同的结果集,但是使用canvasLength排序,所以结果是:
I would like the same result set but sorted using canvasLength so the result is:
8x10
10x10
40x40
推荐答案
我认为您追求的可能是这样的:
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);
更新
根据您问题中的其他信息,以下应做您想做的事情:
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)
这篇关于LINQ:区分和排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!