0

首先,我正在获取 ClientID。然后,我得到与该 ClientID 关联的所有发票。我想返回所有按 InvoiceNumber 排序的数据,降序。这是我的代码:

var rvInvoices =
             (from i in db.QB_INVOICES_HEADER
                where i.ClientID == cId
                select i).ToList();
foreach (var itm in rvInvoices)
{
        InvoiceModel cm = new InvoiceModel()
        {
                InvoiceNumber = itm.InvoiceNumber,
                InvoiceSentDt = itm.InvoiceSentDt,
                InvoiceDt = itm.InvoiceDt,
                Amount = itm.Amount,
                Term = itm.Term,
                ClientName = itm.CI_CLIENTLIST.ClientName
        };

        listInvoices.Add(cm);
}

return listInvoices;
4

5 回答 5

2
listInvoices.OrderByDescending(x => x.InvoiceNumber).ToList()
于 2012-10-16T15:47:07.560 回答
1

你应该尝试这样的事情:

var rvInvoices =
               (from i in db.QB_INVOICES_HEADER
                where i.ClientID == cId
                select i).OrderByDescending(x => x.InvoiceNumber);

而且我看不出你需要打电话的理由.ToList()

于 2012-10-16T15:48:21.837 回答
0

您应该在数据库而不是客户端上订购它们:

var rvInvoices = db.QB_INVOICES_HEADER
    .Where(i => i.ClientID == cId)
    .OrderByDescending(i => i.InvoiceNumber);
于 2012-10-16T15:49:15.610 回答
0

您可以在三个地方下订单。

  1. 在初始查询中,
  2. foreach, 或
  3. 在里面return

选项1:

var rvInvoices =
    (from i in db.QB_INVOICES_HEADER
    where i.ClientID == cId
    select i).OrderByDescending(i => i.InvoiceNumber).ToList();

选项 2:

foreach (var itm in rvInvoices.OrderByDescending(i => i.InvoiceNumber))

选项 3:

return listInvoices.OrderByDescending(i => i.InvoiceNumber).ToList();

我建议采用路线 1,因为它将在数据库级别运行订单。

于 2012-10-16T15:49:46.883 回答
0

您当前拥有的方法创建多个列表,具有显式foreach循环,并且需要对其输出进行排序。只需创建一个列表,无需显式循环,数据库为您进行排序即可完成:

return
    (from i in db.QB_INVOICES_HEADER
     where i.ClientID == cId
     // have the database do the sorting
     orderby i.InvoiceNumber descending
     select i)
     // break out of the DB query to make InvoiceModel
    .ToEnumerable()
    .Select(itm => new InvoiceModel()
    {
        InvoiceNumber = itm.InvoiceNumber,
        InvoiceSentDt = itm.InvoiceSentDt,
        InvoiceDt = itm.InvoiceDt,
        Amount = itm.Amount,
        Term = itm.Term,
        ClientName = itm.CI_CLIENTLIST.ClientName
    })
     // only create one list as the last step
    .ToList();
于 2012-10-16T19:38:32.257 回答