gartenriese
gartenriese

Reputation: 4366

Convert list of elements with list to single list using lambda

I have list of households and each households includes a list of residents. I want to have a function that returns a list of all residents of all households.

What I have so far:

public List<Resident> Residents() {
    var list = new List<Resident>();
    Households.ForEach(x => list.AddRange(x.Residents));
    return list;
}

Is it possible to shorten this with a lambda? Something like this:

public List<Resident> Residents => { ??? }

I know if Households were a list of lists I could use SelectMany, however it is not.

EDIT1:

To make it clear, Household is a class, not a container.

EDIT2:

I tried the following

public List<Resident> Residents => Households.SelectMany(h => h.Residents);

However this gives me the error:

error CS1061: 'List< Household>' does not contain a definition for 'SelectMany' and no extension method 'SelectMany' accepting a first argument of type 'List< Household>' could be found (are you missing a using directive or an assembly reference?)

EDIT3:

Sorry, I thought I was clear. Household is a class which has a list of residents, like this:

class Household {
    public List<Resident> Residents { get; }
}

Upvotes: 2

Views: 104

Answers (4)

Menelaos Vergis
Menelaos Vergis

Reputation: 3955

make sure that you are using System.Linq

using System.Linq;

Households.SelectMany(x => x.Residents) should work no matter if Residents is an array or a List<>

Upvotes: 2

Enigmativity
Enigmativity

Reputation: 117074

You can do this in C# 6.0:

public List<Resident> Residents => Households.SelectMany(x => x.Residents).ToList(); 

You need to make sure that you have a using System.Linq; at the top of your code to get the IEnumerable<T> extension methods - which includes SelectMany.

Upvotes: 4

Mr. B
Mr. B

Reputation: 2975

The following is the shortest I think:

public List<Resident> Residents() 
{
   return Households.SelectMany(x => x.Residents).ToList();
}

Upvotes: 1

Jamiec
Jamiec

Reputation: 136124

Your code can be shortened to

var residents = Households.SelectMany(x => x.Residents).ToList(); 

residents will then be a IEnumerable<Resident> ( or whatever type Residents is, I've assumed its a type called Resident).

You can tag .ToList() on the end if you actually need a List<Resident>.

Upvotes: 3

Related Questions