【问题标题】:How do I apply OrderBy to a Linq Query for a select list如何将 OrderBy 应用于选择列表的 Linq 查询
【发布时间】:2014-05-08 21:41:15
【问题描述】:

我一定遗漏了一些明显的东西。此查询中的 orderby 子句对我的选择列表中显示的项目的顺序没有影响...

List<String> reps = (from r in db.bookings
                     where !r.bookingRep1.Contains("*") && !r.bookingRep1.Contains(" ")
                     orderby r.bookingRep1
                     select r.bookingRep1).Distinct().ToList();

ViewBag.rep1 = new SelectList(reps, booking.bookingRep1);

选择列表...

@Html.DropDownListFor(model => model.bookings.bookingRep1, (SelectList)ViewBag.rep1, "")

我希望选择列表按 bookingrep1 的字母顺序排列

【问题讨论】:

    标签: asp.net-mvc linq entity-framework razor


    【解决方案1】:

    在应用Distinct:

    之后应用订购
    List<string> reps = 
       (from r in db.bookings 
        where !r.bookingRep1.Contains("*") && !r.bookingRep1.Contains(" ") 
        select r.bookingRep1).Distinct().OrderBy(rep => rep).ToList();
    
    ViewBag.rep1 = new SelectList(reps, booking.bookingRep1);
    

    当您将Distinct 应用于有序查询时,则刚刚从生成的 SQL 中删除了排序:

    SELECT
        [Distinct1].[bookingRep1] AS [bookingRep1]
        FROM ( SELECT DISTINCT
            [Extent1].[bookingRep1] AS [bookingRep1]
            FROM [dbo].[bookings] AS [Extent1]
            WHERE [Extent1].[bookingRep1] NOT LIKE @p1 AND 
                  [Extent1].[bookingRep1] NOT LIKE @p2
        )  AS [Distinct1]
    

    当在Distinct 之后应用排序时,它会出现在生成的 SQL 中:

    SELECT
        [Distinct1].[bookingRep1] AS [bookingRep1]
        FROM ( SELECT DISTINCT
            [Extent1].[bookingRep1] AS [bookingRep1]
            FROM [dbo].[bookings] AS [Extent1]
            WHERE [Extent1].[bookingRep1] NOT LIKE @p1 AND 
                  [Extent1].[bookingRep1] NOT LIKE @p2
        )  AS [Distinct1]
        ORDER BY [Distinct1].[bookingRep1] ASC
    

    【讨论】:

    • 完美!谢谢谢尔盖!
    猜你喜欢
    • 2021-04-17
    • 2021-12-30
    • 1970-01-01
    • 2019-05-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-03-03
    • 1970-01-01
    相关资源
    最近更新 更多