在Linq中使用多个包含花费时间来加载性能问题

时间:2019-06-12 10:55:12

标签: c# linq

我在一个表中有60万条记录和20列。

我想使用LINQ查询并使用一个像“ LIKE”一样的函数;因此,我使用了Contains。花费时间(或)会引发超时过期异常。

那么有人可以建议如何解决此问题吗?我需要比较4列以上。

var majorAgents = new[] { "iPhone", "Android", "iPad" };


List<Person> lstperson =_context.person.where 
                      (w=>majorAgents.Any(x=>w.personLastName.contains(x))
                      || majorAgents.Any(x=>w.personFirstName.contains(x))
                      ||w.Address.Any(s=>majorAgents.Contains(s.addressProof)))//Address table referenced as a list 
                        .select(s=> new Person{
                             s.personId,
                             s.perosnLastName,
                             s.personFirstName
                    }).ToList();

2 个答案:

答案 0 :(得分:0)

也许您应该尝试对所有可能的属性仅运行一次majorAgents.Any查询。为此,您可以尝试将firstNamelastNameaddressProof字段进行串联,并检查此串联字符串中的majorAgent字符串是否存在于任何地方。

注意:我故意修改了与Address相关的条件,因为它似乎与当前的任务无关。在原始查询中,它表示:w.Address.Any(s=>majorAgents.Contains(s.addressProof),这意味着“检查majorAgents是否存在addressProof”,而检查addressProof of any Address has any of the majorAgents是否更明智。为此,我将w.Address.SelectMany(a => a.addressProof).ToArray()string.Join一起使用,这将为我提供空格分隔的addressProof字符串,我可以在其中查找任何majorAgent。如果这不是您想要的,请根据需要修改地址的该部分。

因此,尝试的修改后查询为:

var majorAgents = new[] { "iPhone", "Android", "iPad" };


List<Person> lstperson =_context.person.where 
                      (w=>majorAgents.Any(x=>(w.personLastName + " " + w.personFirstName + " " +string.Join(" ",w.Address.SelectMany(a => a.addressProof).ToArray())).contains(x))
                      )
                        .select(s=> new Person{
                             s.personId,
                             s.perosnLastName,
                             s.personFirstName
                    }).ToList();

希望有帮助。

答案 1 :(得分:-1)

执行包含比执行“任何”更有效。 进行以下测试:

var majorAgents = new[] { "iPhone", "Android", "iPad" };

List<Person> lstperson=_context.person.where 
     (c=> majorAgents.contains(c.personLastName) || majorAgents.contains(c.personFirstName))
    .select(s=> new Person{
             s.PersonId,
             s.perosnLastName,
             s.personFirstName
}).ToList();