developer747
developer747

Reputation: 15928

Find all entities using lambda

I have a List<Person> (people) every person has a List<Kid> (kids)

If I want to find all the kids, in LINQ this is what I would do

var kids=new List<Kids>();

foreach(var p in people)
{
    foreach(var kid in p.Kids)
    {
         kids.Add(kid);
    }
}

Is there a one line way of doing this using LINQ?

Upvotes: 3

Views: 1834

Answers (3)

user166390
user166390

Reputation:

A "LINQ-non-lambda-style" version of SelectMany:

var allKids = 
  from p in people
  from k in p.Kids  // secondary "from" makes SelectMany (aka flat map)
  select k;

// Result from above is IEnumerable, to Force evaluation as a List:
List<Kid> allKidsList = allKids.ToList();

Upvotes: 3

mlorbetske
mlorbetske

Reputation: 5649

You can use the SelectMany extension method

var kids = new List(people.SelectMany(person => person.Kids));

Upvotes: 4

Mattias Buelens
Mattias Buelens

Reputation: 20159

It's as simple as SelectMany:

Projects each element of a sequence to an IEnumerable and flattens the resulting sequences into one sequence.

var kids = people.SelectMany(p => p.Kids);

(If you want a List<Kid> instead of an IEnumerable<Kid>, just call .ToList() on the result.)

Upvotes: 13

Related Questions