Ryan Mendoza
Ryan Mendoza

Reputation: 950

Filtering Include values in Linq

With Linq, is there a way to consolidate these two lines into one method chain?

Group group = await _database.Groups.AsQueryable()
    .Include(g => g.Children)
    .Include(g => g.Documents)
    .SingleOrDefaultAsync(g => g.Pk == id);

group.Children = @group.Children.Where(c => c.Active).AsEnumerable().ToList();

Edit to explain structure:

group is of type Group

the Children property on a Group is a List<Group>

Upvotes: 0

Views: 37

Answers (1)

Kevin Smith
Kevin Smith

Reputation: 14436

You could just make the database do the filtering for you instead of bringing back all the children records:

var group = await _database.Groups.AsQueryable()
    .Where(g => g.Pk == id)
    .Select(g => new {
          Children = g.Children.Where(c => c.Active).ToList(),
          Documents = g.Documents.ToList() } )
    .SingleOrDefaultAsync();

Upvotes: 1

Related Questions