golan
golan

Reputation: 13

How to order a list according to a property in the object whose list is a property in the object whose list I want to order?

The title is not very clear. I'll try to explain my problem with code:

I have two classes A and B:

public class A
{
    public List<B> Bs { get; set; }
}

public class B
{
    public DateTime DT { get; set; }
}

and now I have a list of objects of type A and I want to order them, by the DateTime of their Bs. I thought I could do something like this:

private void MyFunc(List<A> As)
{
    var orderedAs = As.OrderBy(a => a.Bs.Select(b => b.DT));
}

Please help me to solve this issue Thanks

Upvotes: 0

Views: 58

Answers (1)

TripleEEE
TripleEEE

Reputation: 509

well you didn't told us what you want to order after so here are some suggestions:

var orderedByMax = As.OrderBy(a => a.Bs.Max(b => b.DT));
var orderedByMin = As.OrderBy(a => a.Bs.Min(b => b.DT));
var orderedByAverage = As.OrderBy(a => a.Bs.Average(b => b.DT.Ticks));
var orderedByAmountOfB = As.OrderBy(a => a.Bs.Count());
var orderedByFirstDTinListofB = As.OrderBy(a => a.Bs.Select(b => b.DT).First());

Upvotes: 1

Related Questions