首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >查询太慢-使用linq查询获取和更新记录

查询太慢-使用linq查询获取和更新记录
EN

Stack Overflow用户
提问于 2016-06-15 13:06:03
回答 2查看 111关注 0票数 2

我有这样的疑问

代码语言:javascript
复制
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();
}

它基于给定的CountryId和CountryName获取cityID,然后更新集合中的相关对象。现在它运行在一个循环中,目前我有5-10项(测试数据)在收集中,它需要明显的时间(明显地慢)。如果在5-10项上慢一些,那么100+项的速度就太慢了.还有别的办法可以让这件事好起来吗?

我将感谢任何帮助

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2016-06-15 13:24:09

根据默里·福克斯克罗夫特的回应,我建立了一个新的查询。我没有您正在使用的对象,但我认为它应该类似于以下内容:

代码语言:javascript
复制
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
            };
票数 3
EN

Stack Overflow用户

发布于 2016-06-15 13:23:46

我猜你的城市里有一个CountryID字段,你根本不需要加入这个州。这是一个简单的代码,没有任何例外的处理:您可能想要尝试找到一个城市,然后让这个国家进入一个try catch块。

代码语言:javascript
复制
    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
        };
    };
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/37836344

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档