Turning a chain of foreach's for inserting elements from a list into
another list into linq
I've been at it for a couple of hours and the only conclusion I achieved
is that I need to pick up a good book about Linq.
So here's the deal: I have three lists of objects of the following classes
(I'll refer to them as "parent lists" from now on:
public class State
{
public int IdState {get; set;}
public string NameState {get; set;}
private IList<City> cityList = new List<City>();
public void AddCity(City city)
{
cityList.Add(city);
}
}
public class City
{
public int IdCity { get; set; }
public string NameCity { get; set; }
public int IdState { get; set; }
private IList<Company> companyList = new List<Company>();
public void AddCompany(Company company)
{
companyList.Add(company);
}
}
public class Company
{
public int IdCompany { get; set; }
public string NameCompany { get; set; }
public int IdCity { get; set; }
}
I think from here is pretty straight forward to explain what I want: A
single list of States, of which cityList is populated with the appropriate
cities in that state and each companyList list in each City is populated
with the companies in that city. In other words, a list of states which
each state branches into its cities and then each city branches into the
companies in them.
So, my parent lists are:
private List<State> finalList; //This is the "parent list supreme"
which I'll send to the client-side
private List<City> cityList; //Auxiliary
private List<Company> companyList; //Auxiliary; this one does not
exist in the actual code but I'm putting it here for simplification
purposes
It really doesn't matter how but thanks to linq "magic", I'm able to fill
up those lists with the proper states, cities and companies, however, I
can't figure out how to fill up the proper cities and companies into
State.cityList and City.companyList through link. As it stands, I'm using
a very ugly chain of foreach's:
foreach (State state in finalList)
{
foreach (City city in cityList)
{
if (city.IdState == state.IdState)
{
state.AddCity(city);
foreach (Company company in companyList)
{
if (line.idCity == city.IdCity)
city.AddCompany(company);
}
}
}
}
Ugly, right? So, how do I go about achieving the same thing with linq? I
think maybe an even more valid question: is it worth using linq in this
case (it all points to "yes" but figures...)?
BTW: this way works just as I expect
No comments:
Post a Comment