0

I have three classes; State, County, and City. State contains a list of County. County contains a list of City.

public class State
{
  public string StateCode;
  List<County> Counties;
  List<string> CitiesInState
  {
    get
    {
      return //LINQ STATEMENT TO GET LIST OF ALL CITYNAMES FROM LIST OF COUNTIES 
    }
  }
}

public class County
{
  public string CountyName;
  List<City> Cities;
}

public class City
{
  public string CityName;
}

I am trying to return a list of all CityNames within the State. Since this is a property of an item that is in a List which is an item within another List, I'm not sure it is possible. I haven't been able to write anything that will even compile. Is this possible? Can someone point my in the right direction?

1
  • 1
    You should use properties, and collections properties should be readonly. Commented Dec 11, 2013 at 20:57

2 Answers 2

4

You're asking how to flatten a nested list:

Counties.SelectMany(c => c.Cities).Select(c => c.CityName)
Sign up to request clarification or add additional context in comments.

Comments

3

It sounds like you just need:

return Counties.SelectMany(county => county.Cities) // IEnumerable<City>
               .Select(city => city.CityName)       // IEnumerable<string>
               .ToList();                           // List<string>

SelectMany (in its simplest form) can be seen as a "flattening" operation - each element of the original collection is projected to another collection, and all the elements of all those "sub-collections" are yielded in turn.

See my Edulinq article on SelectMany for more details, and information about the other overloads. (One of the other overloads could be used to provide the "city to name" projection within SelectMany, but I find this approach more readable.)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.