user6084053
user6084053

Reputation:

linq get all rows then loop to get the value

I think this may be a problem related to syntax. What I want is to query and get all my records from the database and then to use foreach to iterate through the records.

The problem here is that if I query in linq like this:

query:

var balance = db.UserBalance.Where(d => d.ApplicationUserId == userId);

it never recognizes the properties from the balance to construct something like this:

foreach loop

foreach(var i in saldo)
{
    if(balance.value < 0)
    {
        earnings += balance.value;
    }
    else
    {
        expenses -= saldo.value;
    }
}

If someone can give me a tip I would appreciate

PS: Sorry for my bad English

Upvotes: 0

Views: 2026

Answers (2)

Ren&#233; Vogt
Ren&#233; Vogt

Reputation: 43896

It's just guessing as you didn't show your tables etc., but you might want this:

float earnings = 0;
float expenses = 0;
foreach (var balance in db.UserBalance.Where(d => d.ApplicationUserId == userId))
{
    if(balance.value < 0)
        earnings += balance.value;
    else
        expenses -= balance.value;
}

The query returns an enumeration of UserBalances for the given user, which is what you actually want to iterate through.

Upvotes: 1

RB.
RB.

Reputation: 37192

You are getting out a list of balances ("All the records WHERE x is true"), but from your code it appears that you are expecting a unique record.

You can use Single for this.

var balance = db.UserBalance.Single(d => d.ApplicationUserId == userId);

Note that if the record is not guaranteed to exist, use SingleOrDefault and perform a null check on balance.

var balance = db.UserBalance.SingleOrDefault(d => d.ApplicationUserId == userId);
if (balance == null) {
    // No balance was found.
    return;
}

Upvotes: 2

Related Questions