简体   繁体   中英

How can i sort and display <IList> elements in radio button?

I have data IList<String> type in my Model returning string date in yyyyMM format, I need help to display array elements in radio button sorted descending order in MM/yyyy format.

My Model look like as follows:

 public class DataToLoad
 {
        public List<string> Months{ get; set; }       
 }

In my view I have the following to display array element in radio button.

foreach (var record in Model.Months)
{
  <div class="radio col-12">
     <div class="row">
       <div class="col-5" style="">
         @Html.RadioButton("Months", record, true, new { id = record, @class = "m-r" })<label>@record</label>
        </div>
      </div>
   </div>
}

I need if Months return 199008 and 19909, I want to sort values descending and format as MM/yyyy and display the values using radio button 09/1990 first then 08/1990 . Any Help?

You can use this code:

foreach (var record in Model.Months.Select(x=>$"{x.Substring(4,2)}/{x.Substring(0,4)}").OrderByDescending(x=>x))
{
     <div class="radio col-12">
        <div class="row">
          <div class="col-5" style="">
            @Html.RadioButton("Months", record, true, new { id = record, @class = "m-r" })<label>@record</label>
           </div>
         </div>
      </div>
}

Same as any other piece of C# code, use Linq:

   @foreach (var record in Model.Months.OrderBy(x => x))
   {
     <div class="radio col-12">
        <div class="row">
          <div class="col-5" style="">
            @Html.RadioButton("Months", record, true, new { id = record, @class = "m-r" })<label>@record</label>
           </div>
         </div>
      </div>
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM