Reputation: 1574
I'm new to using LiNQ. I have the following code, which is used to find the order quantity of a part on an invoice object.
var invoiceQty = from i in returnInvoices
where i.PartNo == returnPart.PartNo && i.InvoiceID == hiddenInvoiceId.Value
select i.OrderLineQty;
if (Convert.ToInt32(txtReturnProdQty.Text) > Convert.ToInt32(invoiceQty))
{
args.IsValid = false;
SourceValidate.ErrorMessage = "Returned qty cannot be greater than quantity available on the invoice.";
txtReturnProdQty.Focus();
return;
}
I don't think I'm getting the OrderLineQty
value correctly for the if statement, as it generates the following error:
System.InvalidCastException: Unable to cast object of type 'WhereSelectListIterator`2[Invoice,System.Double]' to type 'System.IConvertible'.
Can anyone help me understand how to use the returned value in the LiNQ query?
LiNQ is taking a while to sink in!
Upvotes: 1
Views: 114
Reputation: 7082
Try this way:
if (invoiceQty.FirstOrDefault() != null) return;
if (Convert.ToInt32(txtReturnProdQty.Text) > (decimal)invoiceQty.First())
{
args.IsValid = false;
SourceValidate.ErrorMessage = "Returned qty cannot be greater than quantity available on the invoice.";
txtReturnProdQty.Focus();
return;
}
Upvotes: 0
Reputation: 4628
A linq expression is not evaluated until "used".
This means i.e. calling invoiceQty.ToList() or .First()
Until then invoiceQty type is "an expression" and not the effective type. To get the total quantity you need:
invoiceQty.Sum()
or simply replace the query:
var invoiceQty = (from i in returnInvoices
where i.PartNo == returnPart.PartNo && i.InvoiceID == hiddenInvoiceId.Value
select i.OrderLineQty).Sum();
Upvotes: 1
Reputation: 64
Linq is like a SQL query, if you're familiar with that. In your code, invoiceQty will contain a LIST (more specifically, an IQueryable) of i.OrderLineQty that meet your search criteria in the where clause. Even if there is only one that matches, it will still give you a list with one element.
You look to know for certain only one will match (and the where clause seems to support that assumption), so if your case you can request a Single, First, SingleOrDefault, or FirstOrDefault (click here for a full list of methods available)
if (Convert.ToInt32(txtReturnProdQty.Text) > Convert.ToInt32(invoiceQty.First()))
Upvotes: 0
Reputation: 3095
This is because you are returning an IEnumerable<T>
, if OrderLineQty
is an int, then invoiceQty is of type IEnumerable<int>
.
This is meaningless when you do a comparison.
If you expect only one result then use .Single()
here
Upvotes: 0