2017-06-01 37 views
2

我有以下示例類。OrderBy子集合特定類別

public class Parent 
{ 
    public int Id { get; set; } 
    public List<Child> Children { get; set; } 
} 

public class Child 
{ 
    public string Category { get; set; } 
    public decimal? Price { get; set; } 
} 

和下面的示例數據。

var parents = new List<Parent>() 
{ 
    new Parent() { 
     Id = 1, 
     Children = new List<Child> 
     { 
      new Child {Category = "Item 1", Price = 10 }, 
      new Child {Category = "Item 2", Price = 30 }, 
      new Child {Category = "Item 3", Price = null }, 
      new Child {Category = "Item 4", Price = 5 }, 
      new Child {Category = "Item 5", Price = 20 } 
     } 
    }, 
    new Parent() { 
     Id = 2, 
     Children = new List<Child> 
     { 
      new Child {Category = "Item 1", Price = null }, 
      new Child {Category = "Item 2", Price = null }, 
      new Child {Category = "Item 3", Price = null }, 
      new Child {Category = "Item 4", Price = null }, 
      new Child {Category = "Item 5", Price = null } 
     } 
    }, 
    new Parent() { 
     Id = 3, 
     Children = new List<Child> 
     { 
      new Child {Category = "Item 1", Price = 100 }, 
      new Child {Category = "Item 2", Price = 300 }, 
      new Child {Category = "Item 3", Price = null }, 
      new Child {Category = "Item 4", Price = 50 }, 
      new Child {Category = "Item 5", Price = 200 } 
     } 
    }, 
}; 

我如何使用LINQ訂購Parent對象由Child的價格與具體類別,說‘第3項’?

+0

你的意思是這樣的嗎? parent.OrderBy(x => x.Children.Where(y => y.Category ==「Item 3」)。Max(z => z.Price)); –

+0

這樣做,謝謝。隨意發佈作爲答案,我會接受。 – erdinger

回答

1

你可以做到以下幾點:

parents.OrderBy(x => x.Children.Where(y => y.Category == "Item 3").Max(z => z.Price)); 
1

試試這個:

var resultSet = parents.OrderBy(o => o.Children.Where(e => e.Category == "Item 3").Max(i => i.Price)).ToList(); 
+0

我相信他問的是根據孩子的財產對父母進行分類,但是這會給他一張兒童名單。 –

+0

@FredyTreboux編輯它返回一個父母列表,而不是。 –

+0

謝謝你。但沒有'Min()'或'Max()'我得到'至少有一個對象必須實現IComparable.'異常。 – erdinger