Skip to main content
 首页 » 编程设计

c#之Linq to SQL OrderBy 问题

2024年02月13日12java哥

我知道这个问题已经被问过很多次,我知道 Distinct 调用会破坏之前的订单,所以我必须在之后使用 OrderBy,但在这种情况下,我一定是做错了什么。

int[] resources = (from a in context.Beamline_Requests 
                   join b in context.Technique_Requests on a.Technique_Request_ID equals b.ID 
                   where b.Beamtime_Request_ID == id 
                   select a.Beamline_ID).Distinct().OrderBy(a => a.ID).ToArray(); 

我收到:

Cannot convert lambda expression to type 'System.Linq.Expressions.LambdaExpression' because it is not a delegate type

关于 OrderBy 的错误消息。它还说:

'int' does not contain a definition for 'ID' and no extension method 'ID' accepting a first argument of type 'int' could be found (are you missing a using directive or an assembly reference?)

显然 'a' 不再是上下文的一部分。

我已经成功地完成了类似的事情,但在那些情况下,我将 Linq 投影到 ViewModel 中,因此在这种情况下,它一定与尝试将其变成一个数组有关。

请您参考如下方法:

您只选择字段 Beamline_ID,稍后您尝试OrderBy ID,您选择的中间结果没有字段 ID它只是 int 数字的投影。 As @GrantWinney suggested你可以这样OrderBy(a=> a):

int[] resources = (from a in context.Beamline_Requests 
                   join b in context.Technique_Requests on a.Technique_Request_ID equals b.ID 
                   where b.Beamtime_Request_ID == id 
                   select a.Beamline_ID).Distinct().OrderBy(a => a).ToArray(); 

对于评论:

My issue though is that I actually do need to order by the ID, not the Beamline_ID even though I only need the Beamline_ID in the array.

int[] resources = (from a in context.Beamline_Requests 
                   join b in context.Technique_Requests on a.Technique_Request_ID equals b.ID 
                   where b.Beamtime_Request_ID == id 
                   select new  
                   {  
                       Beamline_ID = a.Beamline_ID, 
                       ID = b.ID 
                   }) 
                   .OrderBy(a => a.ID) 
                   .Select(r=> r.Beamline_ID) 
                   .Distinct() 
                   .ToArray(); 

或者在更简单的版本中你可以实现:

int[] resources = (from a in context.Beamline_Requests 
                   join b in context.Technique_Requests on a.Technique_Request_ID equals b.ID 
                   where b.Beamtime_Request_ID == id 
                   orderby b.ID 
                   select a.Beamline_ID) 
                   .Distinct() 
                   .ToArray();