developer747
developer747

Reputation: 15928

Can this be done with less code using lambda?

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

If I want to find all the People with kids less than 5 years of age, I would do something like this

var peopleWithLittleKids=new List<Person>()

foreach(var p in people)
{
    foreach(var kid in p.Kids)
    {
        if(kid.age<5)
        {
            peopleWithLittleKids.Add(p);
            break;
        }
    }
}

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

Upvotes: 1

Views: 102

Answers (3)

Reed Copsey
Reed Copsey

Reputation: 564373

You can use the Enumerable.Where and Any extension methods:

var peopleWithLittleKids = people.Where(p => p.Kids.Any(k => k.age < 5)).ToList();

Note that you can also leave off ToList() if you are merely going to iterate through the results (via foreach), as that does not require a List<T> for the results.

Also - your loop approach will add a Person to the list multiple times if they have multiple matching children. If you want to duplicate this functionality, you could via:

var peopleWithLittleKidsContainingDuplicates = people
               .SelectMany(p => p.Kids.Where(k => k.Age < 5).Select(k => p));

(This is likely not what you want, and a bug in the original, but this does match the original code...)

Upvotes: 5

spender
spender

Reputation: 120400

Assuming people are allowed have more than one child... [insert political statement here...]

people.Where(p => p.Kids.Any(k => k.age < 5))

Upvotes: 9

Justin Niessner
Justin Niessner

Reputation: 245399

Lambdas alone won't solve your problem. LINQ is the technology that will help you do what you want:

var peopleWithLittleKids = people.Where(p => p.Kids.Any(k => k.age < 5).ToList();

Upvotes: 2

Related Questions