Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

OrderBy Parent object by Nested Collection

Tags:

linq

Simple

public class TimeLine
{
  public String Name {get;set}
  public List<Milestone> MilesStones {get;set}
}

public class Milestone
{
  public String Name {get;set}
  public DateTime Time {get;set}
}

I tried: from t in DataAccess.TimelineCollection.OrderBy(c=>c.MilesStones.OrderBy(z=>z.MilestoneDate)) select t; but got an error that "At least one object must implement IComparable."

I need to order TimeLine by Milestone.Time. First project in a list will be the one that has eraliest Time property in Milestone collection.

Need help with link.

like image 894
dotsa Avatar asked Jun 04 '12 19:06

dotsa


1 Answers

It sounds like you might want

var query = DataAccess.TimelineCollection
                      .OrderBy(t => t.MileStones.Min(m => m.Time));

In other words, for each TimeLine, find the earliest milestone, and use that for ordering.

Of course if the milestones are in order, you could use:

var query = DataAccess.TimelineCollection
                      .OrderBy(t => t.MileStones.First().Time);

Both of these will fail if any TimeLine has no milestones.

like image 198
Jon Skeet Avatar answered Nov 04 '22 08:11

Jon Skeet