如何先按null排序布尔值,然后依次为true和false
return View("Index", db.HolidayRequestForms.ToList().OrderByDescending(e => e.Approved).ThenBy(e => e.RequestID))
我正在为布尔使用自定义显示模板,我不知道这是否重要
答案 0 :(得分:2)
您可以使用自定义比较器
public class ApprovedComparer : IComparer<bool?>
{
public int Compare(bool? x, bool? y)
{
var a = 0;
var b = 0;
if (x.HasValue)
a = x.Value ? 1 : 2;
if (y.HasValue)
b = y.Value ? 1 : 2;
return a - b;
}
}
用法:
return View("Index", db.HolidayRequestForms.ToList()
.OrderBy(e => e.Approved, new ApprovedComparer())
.ThenBy(e => e.RequestID))
可以在LinqPad(或普通的控制台应用程序)中进行测试
public class Thing
{
public string Name { get; set; }
public bool? Approved { get; set; }
}
public class ApprovedComparer : IComparer<bool?>
{
public int Compare(bool? x, bool? y)
{
var a = 0;
var b = 0;
if (x.HasValue)
a = x.Value ? 1 : 2;
if (y.HasValue)
b = y.Value ? 1 : 2;
return a - b;
}
}
void Main()
{
var thing1 = new Thing { Approved = null, Name = "Thing 1" };
var thing2 = new Thing { Approved = true, Name = "Thing 2", };
var thing3 = new Thing { Approved = false, Name = "Thing 3" };
//note the 'incorrect' order
var listOfThings = new[] { thing3, thing2, thing1 };
listOfThings
.OrderBy(x => x.Approved, new ApprovedComparer())
.Select(x => x.Name) //just for outputting the names
.Dump(); //LinqPad specifc
}
输出
从.net 4.5开始,您可以使用Comparer<T>.Create()
创建一个静态比较器,该比较器可以是“内联”的-即,不需要单独的类。
就个人而言,我发现单独的类更易于阅读。不过,只是我的意见。
var comparer = Comparer<bool?>.Create((x, y) =>
{
var a = 0;
var b = 0;
if (x.HasValue)
a = x.Value ? 1 : 2;
if (y.HasValue)
b = y.Value ? 1 : 2;
return a - b;
});
listOfThings
.OrderBy(x => x.Approved, comparer)
.Select(x => x.Name) //just for outputting the names
.Dump(); //LinqPad specifc
答案 1 :(得分:0)
您可以使用此:
myList.OrderBy(v => !v)