Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
4.0k views
in Technique[技术] by (71.8m points)

asp.net mvc - Linq Select OrderBy ThenBy Kendo Dropdownlist

My application is MVC5. I am populating Countries Kendo Dropdownlist, trying to place Canada and United States at the top of the list using:

     public JsonResult GetCountries()
            {
                return Json(db.Country.OrderBy(x => x.TwoCharCountryCode == "CA")
                .ThenBy(x => x.TwoCharCountryCode == "US").ThenBy(x => x.CountryName)
             .Select(c => new { CountryId = c.CountryId, CountryName = c.CountryName }), JsonRequestBehavior.AllowGet);
            }



              @(Html.Kendo().DropDownList()
                  .Name("Country")
                  .HtmlAttributes(new { style = "width:300px;", id="Country", value = ViewBag.CountryId })
                 .OptionLabel("Select country...")
                  .DataTextField("CountryName")
                  .DataValueField("CountryId")
                  .DataSource(source =>
                  {
                      source.Read(read =>
                      {
                          read.Action("GetCountries", "Home");
                      }).ServerFiltering(true);
                  })
                  .Events(e => {e.Select("onSelect");
                  }))

I get Canada and the USA at the bottom! enter image description here

Can I use two ThenBy? or what am I doing wrong?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Just force LINQ translator to create correct query:

var query = db.Country
   .OrderBy(x => x.TwoCharCountryCode == "CA" 
      ? 0 
      : x.TwoCharCountryCode == "US"
      ? 1 : 2)
   .ThenBy(x => x.CountryName)
   .Select(c => new { CountryId = c.CountryId, CountryName = c.CountryName });

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
...