LINQ:Distinct和Orderby

时间:2013-01-31 22:15:01

标签: linq sql-order-by distinct

我正在尝试使用LINQ(到EF)获取DISTINCT列表然后对其进行排序。我找到的所有示例都根据DISTINCT值对结果进行排序。但我想在不同的领域进行排序。

示例:包含2个字段的表(canvasSize和canvasLength);

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

我找到的所有例子都给出了这种答案。但它按canvasSize排序,而我想按canvasLength排序。

我被卡住了...非常感谢任何提示...

Per J. Skeet>其他信息:

company  canvasSize  canvasLength

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

我希望它在canvasSize上有所区别。问题是,在排序时,它会产生以下顺序:

10x10
40x40
8x10  

我想要相同的结果集,但使用canvasLength排序,结果是:

8x10
10x10
40x40

2 个答案:

答案 0 :(得分:12)

我认为你所追求的可能是这样的:

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

<强>更新

根据您问题中的额外信息,以下内容应该符合您的要求:

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

答案 1 :(得分:2)

var sizes = ent.competitors
               .GroupBy(s => s.canvasSize)
               .Select(g => g.First())
               .OrderBy(s => s.canvasLength);