如何解决Linq 选择 OrderBy ThenBy Kendo 下拉列表
我的应用程序是MVC5。我正在填充国家剑道下拉列表,尝试使用以下方法将加拿大和美国置于列表顶部:
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");
}))
我把加拿大和美国放在底部!
我可以使用两个 ThenBy 吗?还是我做错了什么?
解决方法
只需强制 LINQ 转换器创建正确的查询:
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 });
,
当您执行 .OrderBy
或 ThenBy
布尔值时,False
(表示 0)将始终位于 True
(表示 1)之前。
如果您必须将加拿大和美国放在列表的首位,然后对其余部分进行排序,我会先将这两个从列表中删除,然后对列表中的其余部分重新排序,然后将所有内容重新组合在一起:
public JsonResult GetCountries()
{
var canadaOrUsa = db.Country
.Where(x => x.TwoCharCountryCode == "CA" ||
x.TwoCharCountryCode == "US")
.OrderBy(x => x.CountryName);
var theRest = db.Country
.Where(x => x.TwoCharCountryCode != "CA" &&
x.TwoCharCountryCode != "US")
.OrderBy(x => x.CountryName);
return Json(
canadaOrUsa.Concat(theRest)
.Select(x => new {
CountryId = x.CountryId,CountryName = x.CountryName
},JsonRequestBehavior.AllowGet);
}
如果你不想枚举列表两次,我想你可以从你的.ToList()
中db.Country
,找到加拿大和美国,把它们从列表中取出,订购剩下的,然后将它们放回列表的开头。
@configurator 写了一个关于将项目移动到列表顶部的扩展方法:https://stackoverflow.com/a/1668662/2410655
public static IEnumerable<T> MoveToTop(IEnumerable<T> list,Func<T,bool> func) {
return list.Where(func)
.Concat(list.Where(item => !func(item)));
}
您可以使用它来减少需要编写的代码行数:
public JsonResult GetCountries()
{
var result = db.Country
.OrderBy(x => x.CountryName)
.MoveToTop(x => x.TwoCharCountryCode == "CA" ||
x.TwoCharCountryCode == "US");
return Json(
result
.Select(x => new {
CountryId = x.CountryId,JsonRequestBehavior.AllowGet);
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。