我有以下示例类。
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 :(得分:1)
试试这个:
var resultSet = parents.OrderBy(o => o.Children.Where(e => e.Category == "Item 3").Max(i => i.Price)).ToList();
答案 1 :(得分:1)
您可以执行以下操作:
parents.OrderBy(x => x.Children.Where(y => y.Category == "Item 3").Max(z => z.Price));