2013-02-27 282 views
1

我是使用LiNQ的新手。我有以下代碼,用於查找發票對象上零件的訂單數量。查詢結果來自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; 
} 

我不認爲我正確地獲得OrderLineQty值if語句,因爲它會產生以下錯誤:

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

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

LiNQ需要一段時間才能沉入水中!

+0

[呈三角問題] [1] [1]:http://stackoverflow.com/questions/792412/unable-to-cast-object-of-type-system-data-linq-dataquery1system-int32-to-ty 可能是你獲得多重價值 – user1964763 2013-02-27 16:21:24

回答

1

linq表達式直到「使用」才被評估。

這意味着即調用invoiceQty.ToList()或。首先()

直到那時invoiceQty類型是「表達」,而不是有效類型。 得到總的數量,你需要:

invoiceQty.Sum() 

或簡單地替換查詢:

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

這是因爲你是返回一個IEnumerable<T>,如果OrderLineQty是一個int,然後invoiceQty是IEnumerable<int>類型。

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

如果您希望只有一個結果,然後使用.Single()here

0

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

您只能確定一個匹配(並且where子句似乎支持該假設),所以如果您的情況可以請求Single,First,SingleOrDefault或FirstOrDefault(click here以獲取完整的方法列表可用)

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

試試這個方法:

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