Linq然后可能是空的

Bob*_*orn 4 c# linq

我正在尝试对多个属性的视图模型绑定进行排序.问题是第二个属性可能为null,我得到一个空引用异常.

return this.People
  .OrderBy(x => x.Car.Name)
  .ThenBy(x => x.Pet.Name);
Run Code Online (Sandbox Code Playgroud)

如果Pet为null怎么办?我如何按Pet.Name进行ThenBy排序?

Ken*_*rey 10

这应该返回null宠物非宠物之前.

return this.People
  .OrderBy(x => x.Car.Name)
  .ThenBy(x => x.Pet != null ? x.Pet.Name : "");
Run Code Online (Sandbox Code Playgroud)

  • @spender:仅当“ Pet”实现[`IComparable`](http://msdn.microsoft.com/zh-cn/library/4d7sx9hd.aspx)接口时,该方法才有效。 (2认同)