我有兩個表:優化LINQ,而不是創建新的集合/迴路
發票(InvoiceID,InvoiceNumber)
Invoices_Products(InvoiceID,產品ID,IsFinalized)
我展示列表所有發票,並且有按鈕可以通過「定稿」或「未定稿」發票進行過濾。最終發票是每產品是IsFinalized==true
。
此刻,我有以下代碼正在執行非常慢:
IEnumerable<Invoice> invoices = db.Invoices;
if (isFinalized) // filter by finalized invoices
{
List<Invoice> unfinalizedInvoices = new List<Invoice>();
foreach (var invoice in invoices)
{
int invoicesProductsCountTotal = db.Invoices_Products.Where(l => l.InvoiceID == invoice.InvoiceID).Count();
int invoicesProductsCountFinalized = db.Invoices_Products.Where(l => l.InvoiceID == invoice.InvoiceID && l.IsFinalized == true).Count();
if (invoicesProductsCountTotal != invoicesProductsCountFinalized)
{
unfinalizedInvoices.Add(invoice);
}
}
invoices = invoices.Except(unfinalizedInvoices);
}
else
{
List<Invoice> finalizedInvoices = new List<Invoice>();
foreach (var invoice in invoices)
{
int invoicesProductsCountTotal = db.Invoices_Products.Where(l => l.InvoiceID == invoice.InvoiceID).Count();
int invoicesProductsCountFinalized = db.Invoices_Products.Where(l => l.InvoiceID == invoice.InvoiceID && l.IsFinalized == true).Count();
if (invoicesProductsCountTotal == invoicesProductsCountFinalized && invoicesProductsCountFinalized > 0)
{
finalizedInvoices.Add(invoice);
}
}
invoices = invoices.Except(finalizedInvoices);
}
我知道這是不是最佳的,但我喜歡傳播我的LINQ,這樣我可以閱讀和理解它。
我的問題:有沒有什麼辦法可以使這個查詢更快使用.All
或.Any
什麼的,或者我需要重新考慮我的數據庫設計(可能增加一個額外的列在發票表)
編輯:第三張表是產品(ProductID,ProductNumber),但您知道
謝謝。但是我用'Invoices_Products'作爲許多一對多連接表 - 它擁有像「數量」,「SellingPrice」等。(順便說一句,我沒有使用代碼第一 - 第一個使用數據庫)數列 – user982119 2014-09-23 15:42:12
您仍然可以做到這一點,但不是多對多,而是定義兩個一對多的關係。然後你可以用LINQ來遍歷它 – Kenneth 2014-09-23 16:01:35