2013-02-27 302 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; 
}