gpt4 book ai didi

c# - Linq性能查询

转载 作者:太空宇宙 更新时间:2023-11-03 11:00:03 26 4
gpt4 key购买 nike

我的这个查询给出了正确的结果,但它需要大约 15 秒才能运行

int Count= P.Pets.Where(c => !P.Pets.Where(a => a.IsOwned == true)
.Select(a => a.OwnerName).Contains(c.OwnerName) && c.CreatedDate >=
EntityFunctions.AddDays(DateTime.Now, -8)).GroupBy(b=>b.OwnerName).Count();

如果我删除这部分 linq

 '&& c.CreatedDate >= EntityFunctions.AddHours(DateTime.Now, -8)'

运行仅需 3 秒左右。我怎样才能保持相同的情况发生但速度更快?我需要该日期标准,因为我不希望将 8 天前创建的任何类包含在计数中

编辑

我有一个名为 People 的表,在此查询中称为 P,我想返回没有主人的宠物总数,并从查询中删除没有主人的宠物' 确实有一个所有者,即使它们存在于另一个 Pet 引用中也没有该 Pet 的所有者。这意味着如果一个人在 Pets 表中至少有一条记录被视为宠物的主人,那么我想删除返回查询中存在该人的所有情况,一旦完成,只返回已创建的 Pets超过 8 天

最佳答案

您应该缓存日期并将该评估放在首位(因为 DateTime 评估应该比 Contains 评估更快)。还要避免多次重新计算相同的查询。

DateTime eightDaysOld = EntityFunctions.AddHours(DateTime.Now, -8);

//calculate these independently from the rest of the query
var ownedPetOwnerNames = P.Pets.Where(a => a.IsOwned == true)
.Select(a => a.OwnerName);

//Evaluate the dates first, it should be
//faster than Contains()
int Count = P.Pets.Where(c => c.CreatedDate >= eightDaysOld &&

//Using the cached result should speed this up
ownedPetOwnerNames.Contains(c.OwnerName))
.GroupBy(b=>b.OwnerName).Count();

那应该返回相同的结果。 (我希望)

关于c# - Linq性能查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18024393/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com