簡體   English   中英

Linq然后可能是空的

[英]Linq ThenBy Possibly Null

我正在嘗試對多個屬性的視圖模型綁定進行排序。 問題是第二個屬性可能為null,我得到一個空引用異常。

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

如果Pet為null怎么辦? 我如何按Pet.Name進行ThenBy排序?

這應該返回null寵物非寵物之前。

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

如果您希望沒有寵物的人被分類到有寵物的人之上,您可以使用:

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

如果您要進行涉及寵物的許多排序操作,您可以創建自己的繼承自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);
    }
}

現在,您的查詢將如下所示:

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

注意:這將與此答案頂部的查詢相反 - 它會將沒有寵物的人排序到底部(在汽車名稱中)。

您可以對寵物和汽車使用Null對象模式 ,以避免在這種情況下對null進行任何額外檢查,並將可能的NullReferenceException風險降至最低。

使用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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM