Reputation: 131
public class Object1
{
public List<Object2> Logs { get; set; }
}
public class Object2
{
DateTime aDate { get; set; }
}
Now what I am trying to do is to set the order of a
List<Object1>
according to the newest Object2 item in Object1.Logs . How can I do that properly in shorthand with lambda?
Upvotes: 0
Views: 68
Reputation: 2111
var list = new List<Object1>();
/* add your Object1 objects here */
list = list.OrderByDescending(c => c.Logs.Max(d => d.aDate)).ToList();
Upvotes: 0
Reputation: 223187
If you want to order your list in ascending order then you can select the minimum date from the inner list and then use that in OrderBy
like:
var orderedQuery = list.OrderBy(r => r.Logs
.Min(t => t.aDate));
Just make sure to make your property aDate
public
, otherwise it will not be visible outside the class.
In case you are looking to get the latest values first then you need Max
instead of Min
to select the latest date from the inner list, and use OrderByDescending
if you want that particular order.
You can also add check for checking against Empty
and null
something on the lines of:
var orderedQuery = list.OrderBy(r => (r.Logs != null && r.Logs.Any()) ?
r.Logs.Max(t => t.aDate)
: DateTime.MinValue);
Upvotes: 6