Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Andrzejek on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

add calculated column to datatable 2

Status
Not open for further replies.

DotNetGnat

Programmer
Mar 10, 2005
5,548
IN
Hello All,

I have a datatable as shown below

Date | price
_________________
1/1/2010 | 10
1/2/2010 | 11
1/3/2010 | 9
1/4/2010 | 12

I want to add a column to this datatable to result

Date | price | change
______________________
1/1/2010 | 10 |
1/2/2010 | 11 | 1
1/3/2010 | 9 | -2
1/4/2010 | 12 | 3

Any suggestions...

Thanks

-DNG


 
I would do this in the database if possible. Also I would add some sort of key as well.
 
thanks for your input. I also intially thought of doing this at the database level but later changed my mind. Currently in my web app, I generate Datatable on the fly specific for each user based on their inputs. If I could save this table on the database and run sp's on it and return calculated values..which by the way sounds good...but what if I have 100 simultaneous users??

Do you have any suggestions...

-DNG
 
by the way the datatable I generating is sorted by date asc...

-DNG
 
Code:
var table = GetDataTable();
table.Columns.Add("difference", typeof(int));

if(table.Rows.Count < 2) return table;

for(var i=1; i<table.Rows.Count-1; i=i+2)
{
   var currentRow = table.Rows[i];
   var previous = (int)table.Rows[i-1]["price"];
   var current = (int)currentRow["price"];
   currentRow["difference"] = current-previous;
}
return table;

Jason Meckley
Programmer
Specialty Bakers, Inc.

faq855-7190
faq732-7259
 
Thank you Jason...with little tweaking it worked fine...

ca8msm, thanks for the info.

-DNG
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top