【问题标题】:VB LINQ: Order By doesn't work when used with DistinctVB LINQ:与 Distinct 一起使用时,Order By 不起作用
【发布时间】:2013-12-10 21:38:26
【问题描述】:

我知道这应该是一个已解决的问题,但我无法让记录在案的解决方案为我工作。下面的代码假设在 distinct 之后进行排序,但事实并非如此。我参考了这个帖子:LINQ to SQL does not generate ORDER BY when DISTINCT is used?

fyMonth = (From f In DbContext.FYMonth
           Select f.Month).Distinct().OrderBy(Function(n) n).ToList()

我尝试时遇到错误:

OrderBy(Function(n) n.SortOrder)

有什么想法吗?

【问题讨论】:

  • 哦,你不能在 orderby 中使用 n.SortOrder,因为你没有将它包含在你的结果集中......你只是选择了 Month。

标签: vb.net linq


【解决方案1】:

您的查询正在选择月份,并且您得到了不同的月份。一个月不包含 SortOrder 属性,您不再有权访问您的 FYMonth 对象上的该属性。您需要将SortOrder 包含到您的投影中,区分然后对其进行排序,然后投影回月份。

fyMonth = DbContext.FYMonth
    .Select(Function(x) New With { x.Month, x.SortOrder })
    .Distinct
    .OrderBy(Function(x) x.SortOrder)
    .Select(Function(x) x.Month)

这假设每个月的SortOrder 在所有月份都相同。

【讨论】:

    猜你喜欢
    • 2015-07-09
    • 2017-09-24
    • 1970-01-01
    • 1970-01-01
    • 2011-01-28
    • 1970-01-01
    • 2012-04-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多