Reputation: 169
Below are the hierarchies and the required function
public class Friend
{
public string Name { get; set; }
public List<Message> Messages { get; set; }
}
public class Message
{
public string Text { get; set; }
public DateTime Time { get; set; }
}
Now the required function:
public List<string> WhatsApp(List<Friend> friends)
{
throw new NotImplementedException();
}
I need to get the list of friend names in descending order of there message time stamp. Just like Whats App or any other IM for that matter.
I am getting a feeling that this can be done in 1 or 2 lines using LINQ but since I am new to LINQ, unable to drill down the problem.
Thanks in advance for the help.
Upvotes: 2
Views: 1634
Reputation: 205549
If the idea is to order by the last (i.e. max) message timestamp, the following should do the job:
return friends.OrderByDescending(f => f.Messages.Max(m => (DateTime?)m.Time))
.Select(f => f.Name)
.ToList();
Casting to DateTime?
is needed to avoid exception when there are no messages for some friend.
In general when you need to order the parent having multiple children by something based on children properties, it should be some aggregate value (like Sum
, Count
, Min
, Max
etc.).
Upvotes: 4