filtering and sorting a child entity in EF Core

Given this C Sharp class, using EF Core

public class Example
{
    public List<int> Ids { get; set; }
}

You can include related data in an EF Core query, but you'll get everything, as-is. To sort or filter the data you have to first create an anonymous projection, which you can coerce back into the original type.

Example data = _context.Examples
    // 1, 2, 3, 4, 5, 6, 7, 8, 9
    .Include(e => e.Ids)
	.Select(e => new {
	    e,
		// 9, 7, 5, 3, 1
		Ids = e.Ids.Where(i => i % 2 == 0).Sort((x, y) => y - x)
	})
	.Select(x => x.e)
	.Single();

I think the ints would be loaded regardless, as they're a basic type, but you get the idea. The Ids property is loaded/filtered based on C Sharp magic.

A caveat

If the data is already in the context (say, because it was inserted at the start of a run of unit tests) it will not be sorted/filtered. You'll have to do it in-memory instead.

References