2012-06-25 43 views
1

我正在使用c#,sqlce,datatable。我選擇帶有此查詢的產品:在DataTable中過濾結果(date1和date2之間的日期列)

select price from products where productid=myproduct and mydate between startdate and finaldate and clientid=myclient 

但是這需要花費很多時間。 所以我可以用一個數據表來存儲產品:

datatable prices = new datatable(); 
prices=this.returntable("select productid,startdate,finaldate,client from products") 


for(int i=0;i<allproductsihave;i++) { 
    product.newprice=this.getmyprice(prices,product.client,product.id,product.date); 
} 


private decimal getmyprice(datatable products,string myclient, string myproduct, datetime mydate) 
{ 
    //how do I do at here the equivalent to first sql query? 
    //for select a product from a datatable where my date is between 2 dates, 
    //and client=myclient and productid=myproduct 
    return Convert.Todecimal(datatable.prices[something]["price"].tostring()); 
} 

這樣,我不應該連接到數據庫,對每個產品的查詢。 它是否可行?

也許在做convert.todatetime startdate和finaldate?

+1

爲什麼查詢需要很長時間?在productid,clientid,startdate上創建一個索引。無論你在C#中做什麼都不會更快,是嗎? – pilotcam

+0

以及我的老闆不需要查詢,他想要的就像我所描述的 –

+5

你的老闆不是程序員是他嗎?在代碼中執行此操作無法擴展,因爲您正在將整個表加載到內存中。這會導致大量不必要的網絡流量和不必要的內存消耗。另外,通過for循環迭代意味着每個元素都必須迭代,而不管它是否符合條件。除此之外,您正在使用(可能是無類型的)DataTable,並且您測試的每個元素都將導致拆箱操作。這是一個巨大的時間浪費。讓數據庫完成設計的目的會更好。 – JamieSee

回答

0

DataTable.Select()方法接受表示「where」條件的字符串並返回包含匹配行的DataRow數組。

Datarow[] products = prices.Select(string.Format("'{0}'>='{1}' AND '{0}'<='{2}'", mydate, startdate, finaldate)); 

注意日期格式!它必須符合sql。

+0

什麼是指明MyDate這裏? –

2

聽起來像你不想向數據庫發出多個請求,因爲你擔心會做出幾個連接,這會更慢嗎?如果你不想爲每個產品連接,爲什麼不直接使用「('xxx','yyy')」中的產品?然後你有一個查詢調用,並且數據庫沒有改變。您可以在返回時處理結果。

你的老闆應該跟@pilotcam說話。他是對的。它在c#中不會比在數據庫中更快。 :)

事實上,在c#中這樣做意味着你得到的信息(我假設它是一個遠程數據庫通過網絡),你永遠不會使用,所以它可能慢,多少取決於數據是多少在你的數據庫不會在你的最終結果!

1

由於評論中陳述的原因,我不同意這種方法,這裏有一種可能性。這裏的想法是首先檢查最明顯的例外情況,然後以日後的方式工作。

private decimal GetMyPrice(DataTable table, string client, string product, DateTime date) 
    { 
     foreach (DataRow row in table.Rows) 
     { 
      if (row["productid"] != product) continue; 
      if (row["client"] != client) continue; 
      if (Convert.ToDateTime(row["startdate"]) < date) continue; 
      if (Convert.ToDateTime(row["finaldate"]) > date) continue; 

      return Convert.ToDecimal(row["price"]); 
     } 
     throw new KeyNotFoundException();    
    } 
相關問題