Arturo Martinez
Arturo Martinez

Reputation: 385

LinQ Order By on ViewBag

Im trying to order by the registers i take from a LInQ statement before i save them on a List however im not able to do so the items keep getting disordered

This is my LinQ

 foreach (var item in db.Pos.OrderByDescending(x => x.Fecha).Select(l => l.Fecha).Distinct())
        {
           dateday = item.ToString("yyyy-MM-dd");
           var listItem = new SelectListItem { Value = dateday, Text = dateday };
           listItem.Selected = today.Day == item.Day;
           listdate.Add(listItem);

        }
        ViewBag.Fechas = listdate;

But this is my Output on my View:

<select id="Fechas" name="Fechas"><option value="2016-03-06">2016-03-06</option>
<option value="2016-03-04">2016-03-04</option>
<option value="2016-03-07">2016-03-07</option>
<option value="2016-03-01">2016-03-01</option>
<option value="2016-03-02">2016-03-02</option>
<option value="2016-03-05">2016-03-05</option>
<option selected="selected" value="2016-03-08">2016-03-08</option>
<option value="2016-03-03">2016-03-03</option>
</select> 

And this is the output i need:

<select id="Fechas" name="Fechas">
<option selected="selected" value="2016-03-08">2016-03-08</option>
  <option value="2016-03-07">2016-03-07</option>
  <option value="2016-03-06">2016-03-06</option>
  <option value="2016-03-05">2016-03-05</option>
  <option value="2016-03-04">2016-03-04</option>
  <option value="2016-03-03">2016-03-03</option>
  <option value="2016-03-02">2016-03-02</option>
  <option value="2016-03-01">2016-03-01</option>

</select> 

Upvotes: 1

Views: 755

Answers (1)

Servy
Servy

Reputation: 203828

Distinct explicitly states that the order of the results returned is not maintained. You need to order the items after performing the Distinct.

Upvotes: 5

Related Questions