سؤال

I must be missing something obvious. The orderby cluase in this query has no effect on the order of the items displayed in my select list...

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

the select list...

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

I would like the select list to be ordered alphabetically by bookingrep1

هل كانت مفيدة؟

المحلول

Apply ordering after applying 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);

When you apply Distinct to ordered query, then ordering just removed from generated 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]

When ordering is applied after Distinct then its present in generated 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
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top