如何将OrderBy应用于Linq查询以获取选择列表

时间:2014-05-08 21:41:15

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

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

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, "")

我希望selectrep1

按字母顺序排序选择列表

1 个答案:

答案 0 :(得分:5)

在应用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