Matthias Müller
Matthias Müller

Reputation: 3473

LINQ to Entities: Group then Order By

from what I've read, I can use LINQ to first group, then order each Group by using "SelectMany", which is described here: How to group a IQueryable by property 1 but order by property 2?

But this doesn't work for IQueryable I guess.

We basically get a BusinessObject with an Main-Entity and an IEnumable of Entities, so I'd like to first order by the Main-Entity sequence, then by each Name of the Subentities.

So I guess my query would look like this in LINQ to objects:

            var qry = GetQueryFromSomeWhere();
            qry = qry.OrderBy(f => f.MainEntity.SequenceNumber)
                .ThenBy(f => f.SubEntities.SelectMany(f => f.Name)); 

I could order this Names in the Query-Service, but it should be up the consumer to order the entities as he needs.

Is there a possibility to make this work kindahow without loading all Entities in the Memory?

Upvotes: 0

Views: 865

Answers (1)

Oleg
Oleg

Reputation: 1458

If I'am correctly understanding you want to sort records inside each group by record Name. I think that you could accomplish this by ordering records before doing a group by, try this code:

var q = from m in MainEntities
join s in SubEntities on m.Id equals s.MainId
orderby m.SequenceNumber, s.Name
group new { m, s } by m into grp
orderby grp.Key.SequenceNumber
select grp;

Upvotes: 1

Related Questions