簡體   English   中英

從LiNQ查詢中獲取結果

[英]getting result from LiNQ query

我是使用LiNQ的新手。 我有以下代碼,用於查找發票對象上零件的訂購數量。

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

我認為我無法正確獲取if語句的OrderLineQty值,因為它會產生以下錯誤:

System.InvalidCastException: Unable to cast object of type  'WhereSelectListIterator`2[Invoice,System.Double]' to type 'System.IConvertible'.

誰能幫助我了解如何在LiNQ查詢中使用返回值?

LiNQ需要一段時間才能下沉!

直到“使用”,才會評估linq表達式。

這意味着調用invoiceQty.ToList()或.First()

在此之前,invoiceQty類型是“表達式”,而不是有效類型。 要獲得總數量,您需要:

invoiceQty.Sum()

或簡單地替換查詢:

var invoiceQty = (from i in returnInvoices
                 where i.PartNo == returnPart.PartNo && i.InvoiceID == hiddenInvoiceId.Value
                 select i.OrderLineQty).Sum();

這是因為您要返回IEnumerable<T> ,如果OrderLineQty是int,則invoiceQty的類型是IEnumerable<int>

當您進行比較時,這是沒有意義的。

如果只期望一個結果,則在此處使用.Single()

如果您熟悉,Linq就像一個SQL查詢。 在您的代碼中,invoiceQty將包含滿足您的where子句中的搜索條件的i.OrderLineQty的LIST(更具體地說是IQueryable)。 即使只有一個匹配項,它仍然會為您提供一個元素列表。

您可能會確定只有一個匹配(並且where子句似乎支持該假設),因此,如果您遇到這種情況,可以請求Single,First,SingleOrDefault或FirstOrDefault( 單擊此處以獲取可用方法的完整列表)

if (Convert.ToInt32(txtReturnProdQty.Text) > Convert.ToInt32(invoiceQty.First()))

嘗試這種方式:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM