Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sorting by Children in Entity Framework doesn't return sorted list

I know that Entity framework doesn't support sort or filter in the children collections yet. What I thought is that first I get the data then use foreach loop to sort it. The result gives me an unsorted list. My goal is to get the Participants (any order) and CurrentHospitaliztions (order by id descending) which is a child of participants. The models and the query is below. Any help will be appriciated.

public class Participant
{
    public int Id { get; set; }
    .. other fields

    public ICollection<CurrentHospitalization> CurrentHospitalizations { get; set; }

    public Participant()
    {
        CurrentHospitalizations = new Collection<CurrentHospitalization>();
    }
}

public class CurrentHospitalization
{
    public int Id { get; set; }
    .. other fields

    public Participant Participant { get; set; }
    public int ParticipantId { get; set; }

}

The query that I use:

public async Task<IEnumerable<Participant>> GetList()
{
     var participants = await context.Participants
        .Include(x => x.CurrentHospitalizations)
        .ToListAsync();

        foreach (var p in participants )
        {
            var s = p.CurrentHospitalizations;
            foreach (var q in s)
            {
                s.OrderByDescending(u => u.Id);
            }
        }

        return participants ;
}
like image 506
Fabian Avatar asked Feb 02 '26 10:02

Fabian


1 Answers

You sorted the right piece, in the wrong place, and then didn't really do anything with it. You don't need the nested iteration, you can just do it from the single foreach loop like this:

foreach (var p in participants) 
    p.CurrentHospitalizations = p.CurrentHospitalizations.OrderByDescending( ch => ch.Id ).ToList();
like image 148
Travis J Avatar answered Feb 05 '26 00:02

Travis J



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!