简体   繁体   中英

getting result from LiNQ query

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!

A linq expression is not evaluated until "used".

This means ie 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();

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

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()))

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM