21

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?

Flo
  • 729
  • 3
  • 10
  • 22

3 Answers3

31

This might work (untested)...

var clubs = ClubRepository.Where(c=>c.MemberShips.Any(m=>m.User.Age > 45));
Restore the Data Dumps
  • 38,967
  • 12
  • 96
  • 122
  • 4
    FWIW, this approach works, but doesn't really domonstrate how to translate the multiple 'from' statements into LINQ methods. You need the SelectMany method for that (that's what the C# compiler does). – Mark Seemann Oct 27 '09 at 09:39
22

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);
Mark Seemann
  • 225,310
  • 48
  • 427
  • 736
  • 3
    SelectMany() flattens a list of lists... http://stackoverflow.com/questions/958949/difference-between-select-and-selectmany – hagensoft Aug 22 '13 at 01:08
0

A more generic way

List<T> list= new List<T>();
list= object1.NestedList1.SelectMany(x => x.NestedList2).ToList();

Where NestedList2 matches the data type of "list"

James Heffer
  • 686
  • 1
  • 6
  • 17