Bullines
Bullines

Reputation: 5696

Awkward Linq Sort

I have a list of Foo objects:

List<Foo>

Foo itself contains a Bar property, which contains a list of Bazs that have a DateTime property named DateHappened:

public class Foo
{
   public Bar Bar { get; set; }
}

public class Bar
{
   public List<Baz> Baz { get; set; }
}

Is it possible to sort my list of Foos based on the earliest value of the DateHappened property?

Upvotes: 0

Views: 77

Answers (2)

Tim S.
Tim S.

Reputation: 56536

var ordered = fooList.OrderBy(f => f.Bar.Baz.Min(b => b.DateHappened));

Upvotes: 4

Lee
Lee

Reputation: 144126

var ordered = fooList
    .SelectMany(f => f.Bar.Bazs.Select(b => new { Foo = f, DT = b.DateTime }))
    .OrderBy(fd => fd.DT)
    .Select(fd => fd.Foo);

If you want to order by the minimum time in each Baz list you can do:

var ordered = fooList
    .OrderBy(f => f.Bar.Bazs.Select(b => b.DateTime).Min());

Upvotes: 0

Related Questions