【发布时间】:2013-08-22 19:42:57
【问题描述】:
我已经研究了几个小时,我得到的唯一结论是我需要拿起一本关于 Linq 的好书。
所以这是交易:我有以下类的三个对象列表(从现在开始我将它们称为“父列表”:
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; }
}
我认为从这里可以很直接地解释我想要什么:一个州列表,其中 cityList 填充了该州的适当城市,每个城市中的每个 companyList 列表都填充了该城市的公司.换句话说,一个州列表,每个州分支到其城市,然后每个城市分支到其中的公司。
所以,我的父母名单是:
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
真的没关系,但多亏了 linq“魔法”,我能够用正确的州、城市和公司填写这些列表,但是,我不知道如何填写正确的城市和公司通过链接进入 State.cityList 和 City.companyList。就目前而言,我正在使用一个非常丑陋的 foreach 链:
foreach (State state in finalList)
{
foreach (City city in cityList)
{
if (city.IdState == state.IdState)
{
state.AddCity(city);
foreach (Company company in companyList)
{
if (company.idCity == city.IdCity)
city.AddCompany(company);
}
}
}
}
丑陋,对吧?那么,我该如何用 linq 实现同样的目标呢?我认为可能是一个更有效的问题:在这种情况下是否值得使用 linq(它都指向“是”但数字......)?
顺便说一句:这种方式正如我所期望的那样工作
【问题讨论】:
-
我不明白你想要达到什么目的。 finalList 是否预先填充了州,而您只是想将城市和公司插入到孩子中?还是倒过来了?
-
在您的示例代码中,这部分令人困惑:
if (line.idCity == city.IdCity)因为它在父 foreach 的上下文中似乎没有意义。在 foreach 中既没有更改 line 也没有更改 city,因此如果这是正确的,是否应该将其移到 foreach 之外,因为它对于 companyList 的所有迭代总是为真或总是为假? -
@RobertMcKee 感谢您指出这一点,这是一个“剩余代码”,因为在实际代码中我不使用公司的支持列表。已编辑以符合要求。