c# 4.0 - Maximum value in datatable column c# -
i have set of text files reading datatable. want able read frist column (id) , find out highest number. each of files goes 0 @ least 21 sequentially. tried suggestions following link: how select min , max values of column in datatable?
sadly, not work. 1 suggestion kind of worked shown in second last line, returns value of 8 or 9. suggestions how results looking for?
string filepath = system.io.path.getfullpath(curriculum); datatable curriculmdatatable = new datatable(); curriculmdatatable.columns.add("id"); curriculmdatatable.columns.add("course"); curriculmdatatable.columns.add("credit"); // read in file line-by-line, , store var txtfileline = file.readalllines(filepath).tolist(); //reads line splits data colums @ tab (ascii value 9) txtfileline.foreach(line => curriculmdatatable.rows.add(line.split((char)9))); //suggestions link int max = convert.toint32(curriculmdatatable.select("id=max(id)")[0][0]); label1.text = ""+ max;
the problem have created string columns want max-values according numeric value. best way store corrrect type in first place. either use datatable.compute
or linq-to-dataset
:
create int
column:
curriculmdatatable.columns.add("id", typeof(int));
convert strings
int
, add them table:
foreach(string line in file.readlines(filepath)) { datarow row = curriculmdatatable.rows.add(); string[] fields = line.split(new[]{(char)9}); int id; if(fields.length == 3 && int.tryparse(fields[0], out id) { row.setfield("id", id); row.setfield("course", fields[1]); row.setfield("credit", fields[2]); } }
now can use linq:
int maxid = curriculmdatatable.asenumerable().max(r => r.field<int>("id"));
datatable.compute
(works earlier .net versions):
int maxid = (int)curriculmdatatable.compute("max(id)", "")
Comments
Post a Comment