Linq然后可能是空的

时间:2012-06-30 23:57:55

标签: c# linq

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

return this.People
  .OrderBy(x => x.Car.Name)
  .ThenBy(x => x.Pet.Name);

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

4 个答案:

答案 0 :(得分:9)

这应该在非零宠物之前返回null宠物。

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

答案 1 :(得分:3)

如果您希望没有宠物的人被分类到有宠物的人之上,您可以使用:

return 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());

注意:这将与此答案顶部的查询相反 - 它会将没有宠物的人排序到底部(在汽车名称中)。

答案 2 :(得分:2)

您可以将Null Object pattern用于宠物和汽车,以避免在这种情况下对null进行任何额外检查,并将可能的NullReferenceException风险降至最低。

答案 3 :(得分:0)

一起使用空条件(?.)和空合并(??)运算符,您可以做到这一点-

return this.People
  .OrderBy(x => x.Car.Name)
  .ThenBy(x => x.Pet?.Name ?? string.Empty);
相关问题