2017-06-01 79 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