我有这个查询
foreach (var item in collection)
{
var countrylist = from country in countryList
where
(from state in stateList
where
(from city in cityList
where
city.CityID == item.CityID
select new
{
city.CountryID
}).Contains(new { StateID = state.StateID })
select new
{
state.CountryID
}).Contains(new { CountryID = country.CountryID })
select new
{
CountryID = country.CountryIDD,
Name = country.Name
};
item.Country = new Country();
item.Country.CountryID = countrylist.Select(s => s.CountryID).FirstOrDefault();
item.Country.Name = countrylist.Select(s => s.CountryName).FirstOrDefault();
}
它根据给定的cityID获取CountryId和CountryName,然后更新集合中的相关对象。现在它在一个循环中运行,目前我在集合中有5-10个项目(测试数据),它需要很长时间(明显很慢)。如果在5-10个项目上它的速度很慢,那么100个项目的速度会太慢。还有另一种方法可以让这件事变得更好吗?
我会感谢任何形式的帮助
答案 0 :(得分:3)
根据Murray Foxcroft的回复,我建立了一个新的查询。我没有你正在使用的对象,但我认为它看起来应该类似于:
var countrylist = from country in countryList
join state in stateList
on country.CountryID = State.CountryID
join city in cityList
on state.StateID = city.StateID
where
city.CityID == item.CityID
select new
{
CountryID = country.CountryIDD,
Name = country.Name
};
答案 1 :(得分:0)
我猜你的城市里面有一个CountryID字段,你根本不需要加入该州。这是一个没有异常处理的简单代码:您可能想尝试查找一个城市,然后在try catch块中获取该国家。
foreach (var item in collection)
{
var country = countryList.Find(c=> c.CountryID == cityList.Find(c => c.CityID == item.CityID).StateId);
item.Country = newCountry
{
CountryID = country.CountryIDD,
Name = country.Name
};
};