Add two IQueryables (int/decimal) in C#
I am pulling two values from a MYSQL database. I have one int and one deci开发者_JAVA技巧mal...how do I add them?
Currently, my code is:
orderTotal += cartItem.Count * storeDB.Designs.Select(p => p.Price);
// countItem.Count = int
// storeDB.select = decimal
How do I add these? I've tried type casting every which way. Any help is appreciated!
.Select()
returns a collection, which can't be cast to the operand of a multiplication, even if it only contains one item. Take a look at FirstOrDefault()
and its kin, which return scalars.
If you're expecting more than one value, you'll need to aggregate Designs
with something like Sum()
before multiplying the result.
The result of storeDB.Designs.Select(p => p.Price)
is not a decimal. It is an IEnumerable<decimal>
. Your logic should look something like this:
orderTotal += cartItem.Count *
storeDb.Designs.First(d => d.Id == cartItem.Id).Price;
Keep in mind that First
will throw if there is not an item in the database with the right id ( cartItem.Id
).
精彩评论