Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to query a nested list using a lambda expression

Tags:

lambda

linq

In my repository implementation I can run the following query using a lambda expression:

public IList<User> GetUsersFromCountry(string)
{
    return _UserRepository.Where(x => x.Country == "Sweden").ToList();                  
}

So far so good, simple stuff. However, I'm having difficulties to write a lambda expression against a nested -> nested list. Given the following example (sorry couldn't think of a better one):

The following query works absolutely fine and returns all clubs, which have members over the age of 45

public IList<Clubs> GetGoldMembers()
        {
            var clubs =   from c in ClubRepository
                          from m in c.Memberships 
                          where m.User.Age  >  45
                          select c;

            return clubs;
        }

At the moment, this is where my knowledge of lambda expression ends.

How could I write the above query against the ClubRepository, using a lambda expression, similar to the example above?

like image 413
Flo Avatar asked Oct 26 '09 20:10

Flo


2 Answers

This might work (untested)...

var clubs = ClubRepository.Where(c=>c.MemberShips.Any(m=>m.User.Age > 45));
like image 173
Jason Punyon Avatar answered Nov 03 '22 08:11

Jason Punyon


Here's one way to do it:

var clubs = clubRepository
    .SelectMany(c => c.Memberships, (c, m) => new { c, m })
    .Where(x => x.m.User.Age > 45)
    .Select(x => x.c);
like image 22
Mark Seemann Avatar answered Nov 03 '22 09:11

Mark Seemann