如何在foreach循环中抓取数据后返回数据?

时间:2012-10-16 15:45:42

标签: c# sql asp.net-mvc

首先,我抓住了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;

5 个答案:

答案 0 :(得分:2)

listInvoices.OrderByDescending(x => x.InvoiceNumber).ToList()

答案 1 :(得分:1)

你应该尝试这样的事情:

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

我没有理由要求您致电.ToList()

答案 2 :(得分:0)

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

var rvInvoices = db.QB_INVOICES_HEADER
    .Where(i => i.ClientID == cId)
    .OrderByDescending(i => i.InvoiceNumber);

答案 3 :(得分:0)

您可以在三个地方执行订单。

  1. 在初始查询中,
  2. foreach
  3. return
  4. 选项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,因为它将在数据库级别运行命令。

答案 4 :(得分: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();