我正在尝试对一个视图模型进行多属性排序绑定。问题是第二个属性可能为空,从而导致出现空引用异常。
return this.People
.OrderBy(x => x.Car.Name)
.ThenBy(x => x.Pet.Name);
如果Pet为null,我该如何按Pet.Name进行ThenBy排序?
这应该返回 null 宠物在非null宠物之前。
return this.People
.OrderBy(x => x.Car.Name)
.ThenBy(x => x.Pet != null ? x.Pet.Name : "");
x.Pet != null ? x.Pet.Name : ""
替换为更简洁(且不易出错)的空值合并运算符如何? x.Pet ?? string.Empty
- spenderreturn this.People
.OrderBy(x => x.Car.Name)
.ThenBy(x => x.Pet == null ? string.Empty : x.Pet.Name);
如果您需要进行许多涉及宠物的排序操作,可以创建一个自己的PetComparer
类,该类继承自Comparer<Pet>
,如下所示:
public class Pet
{
public string Name { get; set; }
// other properties
}
public class PetComparer : Comparer<Pet> //
{
public override int Compare(Pet x, Pet y)
{
if (x == null) return -1; // y is considered greater than x
if (y == null) return 1; // x is considered greater than y
return x.Name.CompareTo(y.Name);
}
}
return this.People
.OrderBy(x => x.Car.Name)
.ThenBy(x => x.Pet, new PetComparer());
NullReferenceException
的风险。?.
)和空合并(??
)运算符,您可以这样做 -return this.People
.OrderBy(x => x.Car.Name)
.ThenBy(x => x.Pet?.Name ?? string.Empty);