【问题标题】:Order by not working in LINQ query通过不在 LINQ 查询中工作进行排序
【发布时间】:2013-10-21 08:57:38
【问题描述】:

我正在使用 Linq to SQL 框架(DBML 文件)使用以下查询。这是来自上一个问题 - Inner Join in LINQ not working correctly

Order By 部分似乎不起作用。它只是按标题排序,然后按开始日期排序。我怎样才能让查询仅在开始日期之前订购?

Dim ds = From tds In db.tbl_tripDeptStations _
                Join s In db.tbl_Stations On tds.tds_Stn Equals s.stn_ID _
                Where s.stn_County.Equals(county) _
                Select New With {tds.tds_Trip}

        Dim result = (From t In db.tbl_Trips _
                      Join ds2 In ds On t.trip_ID Equals ds2.tds_Trip _
                      Join toop In db.tbl_TourOperators On t.tourOp_ID Equals toop.tourOp_ID _
                      Where t.trip_StartDate >= startDate And t.trip_EndDate <= endDate And t.trip_StartDate >= Date.Today() _
                      Order By t.trip_StartDate _
                      Select New With {t.trip_ID, t.trip_Name, t.trip_StartDate, toop.tourOp_Name}).Distinct()

【问题讨论】:

  • 如果您删除 .Distinct(),ORDER BY 是否有效?
  • 啊,是的,谢谢 - 已经解决了。我需要那里的独特之处吗?如果没有它,似乎返回的结果数量相同。在这种特殊情况下 distinct 是如何工作的?再次感谢。
  • 我认为这取决于ds 子查询是否可以返回重复的trip_ID。如果它可以返回重复项,您可以在 Linq 中将 Join ds2 In ds ... 重写为等效的 EXISTS
  • 您也可以在查询的.Distinct() 部分执行,然后在之后执行您的.OrderBy()

标签: sql vb.net linq


【解决方案1】:

除了ThenBy 类型的操作符之外,不能保证操作符保持顺序(其中很多实际上并没有保证,因为实现起来很复杂/很慢)。

如果您希望您的查询代表一个有序集合,您应该在查询中最后调用 OrderBy 类型的运算符,在您的情况下,您在最后使用 Distinct 会破坏顺序保证,它并不特定于 distinct at许多其他运营商都可能发生所有事情

对于您的示例,按您放置的位置删除顺序,并在不同后添加:

.OrderBy(item=>item.trip_StartDate);

【讨论】:

  • 感谢您的回复。不幸的是,“项目”部分无法识别。它只是在 Visual Studio 中用红色下划线。我需要将其更改为什么?
  • 您不需要更改它,项目在同一个地方定义和使用,您需要向我展示您输入的内容以便我告诉您要更改的内容,所以请更新您的对您现在无法正常工作的代码提出问题。
猜你喜欢
  • 1970-01-01
  • 2016-10-27
  • 2021-09-25
  • 2017-09-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多