[英]Linq ThenBy Possibly Null
I'm trying to sort a view model binding on multiple properties. 我正在尝试对多个属性的视图模型绑定进行排序。 The problem is that the second property might be null, and I get a null reference exception.
问题是第二个属性可能为null,我得到一个空引用异常。
return this.People
.OrderBy(x => x.Car.Name)
.ThenBy(x => x.Pet.Name);
What if Pet is null? 如果Pet为null怎么办? How do I still do a ThenBy sort by Pet.Name?
我如何按Pet.Name进行ThenBy排序?
This should return null Pets before non-null Pets. 这应该返回null宠物非宠物之前。
return this.People
.OrderBy(x => x.Car.Name)
.ThenBy(x => x.Pet != null ? x.Pet.Name : "");
If you want people with no pets to be sorted above those with pets, you can use this: 如果您希望没有宠物的人被分类到有宠物的人之上,您可以使用:
return this.People
.OrderBy(x => x.Car.Name)
.ThenBy(x => x.Pet == null ? string.Empty : x.Pet.Name);
If you're going to be doing many sort operations involving pets, you could make your own PetComparer
class that inherits from Comparer<Pet>
, like this: 如果您要进行涉及宠物的许多排序操作,您可以创建自己的继承自
Comparer<Pet>
的PetComparer
类,如下所示:
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);
}
}
Now, your query would look like this: 现在,您的查询将如下所示:
return this.People
.OrderBy(x => x.Car.Name)
.ThenBy(x => x.Pet, new PetComparer());
Note: this will do the opposite of the query at the top of this answer--it will sort people without pets to the bottom (within a car name). 注意:这将与此答案顶部的查询相反 - 它会将没有宠物的人排序到底部(在汽车名称中)。
您可以对宠物和汽车使用Null对象模式 ,以避免在这种情况下对null进行任何额外检查,并将可能的NullReferenceException
风险降至最低。
Using the null conditional ( ?.
) and null coalescing ( ??
) operators together you can do this - 使用null条件(
?.
)和null合并( ??
)运算符可以做到这一点 -
return this.People
.OrderBy(x => x.Car.Name)
.ThenBy(x => x.Pet?.Name ?? string.Empty);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.