按子集合中的属性对父实体进行排序

时间:2012-11-13 09:06:31

标签: c# linq linq-to-sql

我有以下课程:

public class Order
{
     public int Oid {get; set;}
     public DateTime OrderDate {get; set;}
     public List<OrderDetails> OrderDetails {get; set;}     
}

public class OrderDetail
{
     public int Oid {get; set;}
     public int Price {get; set;} 
     public Order Order {get; set;}     
     public EventSchedule EventSchedule {get; set;}            
}

public class EventSchedule
{
     public int Oid {get; set;}                 
     public BaseEvent BaseEvent {get; set;}     
     public List<OrderDetail> OrderDetails {get; set;}           
}  

public class BaseEvent
{
     public int Oid {get; set;}  
     public string Name {get; set;}               
     public List<EventSchedule> EventSchedules {get; set;}
}

我有以下代码:

var result = Database.Orders.Where(o => o.DateTime == dateTime);

现在,我想对result

进行排序
case "Date":
       result = (sortingOrder == "desc") ? result.OrderByDescending(c => c.OrderDate) : result.OrderBy(c => c.OrderDate);
       break;

 // the problem is here this code not works
case "EventName":
      result = (sortingOrder == "desc") ? result.All(o=>o.OrderDetails.OrderBy(d=>d.EventSchedule.BaseEvent.Name)) : ...;
      break;

Order的集合为OrderDetailOrderDetailEventSchedule。并且EventScheduleBaseEvent。这可以通过Order中的Name属性对BaseEvent对象进行排序吗?

1 个答案:

答案 0 :(得分:2)

这个怎么样?

case "EventName":
    result = results.OrderBy(
        r => r.OrderDetails.Select(
            od => od.EventSchedule.BaseEvent.Name).Distinct().FirstOrDefault());
//...