C# Linq然后可能为空
我正在尝试对多个属性上的视图模型绑定进行排序。问题是第二个属性可能为null,我得到一个null引用异常C# Linq然后可能为空,c#,linq,C#,Linq,我正在尝试对多个属性上的视图模型绑定进行排序。问题是第二个属性可能为null,我得到一个null引用异常 return this.People .OrderBy(x => x.Car.Name) .ThenBy(x => x.Pet.Name); 如果Pet是空的呢?我如何仍然按宠物名称进行ThenBy排序?如果您希望没有宠物的人的排序高于有宠物的人,您可以使用以下方法: return this.People .OrderBy(x => x.Car.Name)
return this.People
.OrderBy(x => x.Car.Name)
.ThenBy(x => x.Pet.Name);
如果Pet是空的呢?我如何仍然按宠物名称进行ThenBy排序?如果您希望没有宠物的人的排序高于有宠物的人,您可以使用以下方法:
return this.People
.OrderBy(x => x.Car.Name)
.ThenBy(x => x.Pet == null ? string.Empty : x.Pet.Name);
如果要执行许多涉及pets的排序操作,可以创建自己的PetComparer
类,该类继承自Comparer
,如下所示:
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());
注意:这将与此答案顶部的查询相反——它将把没有宠物的人排到底部(在汽车名称内)。这将在非空宠物之前返回空宠物
return this.People
.OrderBy(x => x.Car.Name)
.ThenBy(x => x.Pet != null ? x.Pet.Name : "");
在这种情况下,您可以将其用于宠物和汽车,以避免对null进行任何额外检查,并将可能出现的
NullReferenceException
风险降至最低 同时使用空条件(?。
)和空合并(?
)运算符可以完成此操作-
return this.People
.OrderBy(x => x.Car.Name)
.ThenBy(x => x.Pet?.Name ?? string.Empty);
你想先点还是最后点零宠物?很好。我应该这么做。其他人直接回答了这个问题。谢谢更换
x.Pet!=无效的x、 Pet.Name:“
使用更简洁(且不易被键入)的空合并运算符<代码>x.Pet??string.Empty@spender:只有当Pet
实现Interface.Oops时,这才有效。误读了答案Pet
s不一定是字符串。没问题……我确实添加了一些额外的内容。我对此表示感谢。回答得很好。