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; }
}