在DataTable中过滤结果(date1和date2之间的日期列)

时间:2012-06-25 22:47:17

标签: c# datetime date datatable

我正在使用c#,sqlce,datatable。我选择带有此查询的产品:

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?

3 个答案:

答案 0 :(得分:2)

听起来你不想对数据库发出多个请求,因为你担心要建立几个连接,这会更慢?如果你不想连接每个产品,为什么不直接使用“'('xxx','yyy')中的产品?”然后,您只有一个查询调用,并且数据库没有任何更改。然后,您可以在取回结果时处理结果。

你的老板应该和@pilotcam说话。他是对的。它在c#中没有比在数据库上更快。 :)

事实上,在c#中执行此操作意味着您将获得您不会使用的信息(我假设它是一个远程数据库的网络),所以它可能更慢,多少取决于您的数据库中有多少数据哪个不会出现在你的最终结果中!

答案 1 :(得分:1)

DataTable.Select()方法接受表示“where”条件的字符串,并返回包含匹配行的DataRow数组。

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

记住日期格式!!它必须符合sql。

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