Decastrio
Decastrio

Reputation: 133

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);
        }
   }

it's my code works so slowly, because of getting date but it is not necessary, i don't know other way. maybe something like :

db.Currency.Find().Value.Equals(current.Value).where...where...

Upvotes: 3

Views: 147

Answers (2)

Ghasem
Ghasem

Reputation: 15573

You can do all your conditions in just one where, and also you can skip having a bool variable to check your conditions

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);
}

Upvotes: 4

Patrick Hofman
Patrick Hofman

Reputation: 156978

I think your main problem is the .Count(x => x.Id > 0), which forces the evaluation of all the conditions before and actually get the total number.

If you can, replace it with Any. In that way, it just has to get one row at most:

bool isBeing = db.Currency
               .Where(x => x.ForDate == current.ForDate
                           && x.TitleId == current.TitleId
                           && x.Value == current.Value
                           && x.Id > 0
                     )
               .Any();

Upvotes: 8

Related Questions