1

I am using c#, sqlce, datatable. I select products with this query:

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

But it's going to take much time. So I could use a datatable to store products:

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());
 }

In this way I shouldn't connect to the database for each product query. Is it posible?

maybe doing convert.todatetime to startdate and finaldate?

4

3 回答 3

2

Sounds like you dont want to make multiple requests to the database because you are worried about making several connections, which will be slower? If you dont want to connect for every product, why not just use a "where product in ('xxx', 'yyy')" instead? Then you have a single query call, and no changes on the database. You can then process the results when you get them back.

Your boss should speak to @pilotcam. He is right. Its no quicker in c# than it would be on the database. :)

In fact, doing this in c# means you are getting information back (I assume over a network if its a remote database) which you would never use, so its probably slower, how much depends on how much data is in your database which wont be in your final results!

于 2012-06-25T23:10:50.483 回答
1

The DataTable.Select() method accepts a string representing a "where" condition and returns an array of DataRow containing matching rows.

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

Mind the date format!! It must be sql compliant.

于 2012-06-25T23:07:37.263 回答
1

As much as I disagree with this method for reasons stated in comments, here's one possibility. The idea here is to check for the most obvious exclusions first, then work your way to the date later.

    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();               
    }
于 2012-06-25T23:25:35.707 回答