【问题标题】:getting result from LiNQ query从 LiNQ 查询中获取结果
【发布时间】:2013-02-27 16:17:12
【问题描述】:

我是使用 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 需要一段时间才能融入其中!

【问题讨论】:

标签: c# asp.net linq


【解决方案1】:

一个 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();

【讨论】:

    【解决方案2】:

    这是因为您返回的是 IEnumerable<T>,如果 OrderLineQty 是 int,则 invoiceQty 的类型为 IEnumerable<int>

    当你进行比较时,这是没有意义的。

    如果您只期望一个结果,请使用 .Single() here

    【讨论】:

      【解决方案3】:

      Linq 就像一个 SQL 查询,如果您熟悉的话。在您的代码中,invoiceQty 将包含一个 i.OrderLineQty 的 LIST(更具体地说,一个 IQueryable),它满足您在 where 子句中的搜索条件。即使只有一个匹配,它仍然会给你一个包含一个元素的列表。

      您希望确定只有一个匹配(并且 where 子句似乎支持该假设),因此如果您的情况可以请求 Single、First、SingleOrDefault 或 FirstOrDefault(click here 的完整列表可用的方法)

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

      【讨论】:

        【解决方案4】:

        试试这个方法:

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

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2011-04-05
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多