如何加速 C#/Linq 查询? [我不需要获取数据,我需要获取条件]
How to accelerate C#/Linq query? [i don't need to get data, i need to get condition]
public int being = 0;
public void Insert(Currency current, int number)
{
being = db.Currency.Where(x => x.ForDate == current.ForDate)
.Where(x => x.TitleId == current.TitleId)
.Where(x => x.Value == current.Value).Count(x=>x.Id > 0);
if (being == 0)
{
db.Currency.AddOrUpdate(current);
}
}
这是我的代码运行如此缓慢的原因,因为要获取日期,但这不是必需的,我不知道其他方式。
也许是这样的:
db.Currency.Find().Value.Equals(current.Value).where...where...
我认为你的主要问题是.Count(x => x.Id > 0)
,它强制评估之前的所有条件并实际获得总数。
可以的话换成Any
。这样,它最多只需要一行:
bool isBeing = db.Currency
.Where(x => x.ForDate == current.ForDate
&& x.TitleId == current.TitleId
&& x.Value == current.Value
&& x.Id > 0
)
.Any();
您可以在一个 where
中完成所有条件,也可以跳过 bool
变量来检查您的条件
if(db.Currency.Where(x => x.ForDate == current.ForDate
&& x.TitleId == current.TitleId && x.Value == current.Value && x.Id > 0).Any())
{
db.Currency.AddOrUpdate(current);
}
public int being = 0;
public void Insert(Currency current, int number)
{
being = db.Currency.Where(x => x.ForDate == current.ForDate)
.Where(x => x.TitleId == current.TitleId)
.Where(x => x.Value == current.Value).Count(x=>x.Id > 0);
if (being == 0)
{
db.Currency.AddOrUpdate(current);
}
}
这是我的代码运行如此缓慢的原因,因为要获取日期,但这不是必需的,我不知道其他方式。 也许是这样的:
db.Currency.Find().Value.Equals(current.Value).where...where...
我认为你的主要问题是.Count(x => x.Id > 0)
,它强制评估之前的所有条件并实际获得总数。
可以的话换成Any
。这样,它最多只需要一行:
bool isBeing = db.Currency
.Where(x => x.ForDate == current.ForDate
&& x.TitleId == current.TitleId
&& x.Value == current.Value
&& x.Id > 0
)
.Any();
您可以在一个 where
中完成所有条件,也可以跳过 bool
变量来检查您的条件
if(db.Currency.Where(x => x.ForDate == current.ForDate
&& x.TitleId == current.TitleId && x.Value == current.Value && x.Id > 0).Any())
{
db.Currency.AddOrUpdate(current);
}