Linq to SQL OrderBy issue



我知道这个问题已经被问过很多次了,我知道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();

我收到:

无法将lambda表达式转换为类型"System.Linq.Expressions.LambdaExpression",因为它不是委托类型

CCD_ 1上的错误消息。它还说:

"int"不包含"ID"的定义,也找不到接受"int"类型的第一个参数的扩展方法"ID"(是否缺少using指令或程序集引用?)

因此,显然"a"已不再是上下文的一部分。

我已经成功地做了类似的事情,但在这些情况下,我将Linq投影到ViewModel中,所以在这种情况下,它一定与试图将其作为数组有关。

您只选择字段Beamline_ID,然后尝试OrderBy ID,您从select得到的中间结果没有字段ID,它只是int数字的投影。正如@GrantWinney建议的那样,你可以像一样做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();

评论:

不过,我的问题是,我确实需要按ID订购,而不是Beamline_ID,尽管我只需要数组中的Beanline_ID。

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();

最新更新