c# - How can I find whether datatables have same no of rows and same filenames in each row -
in c# application have 3 datatables:
datatable1
dataview view = wavdt.defaultview; view.sort = "wfname"; dt1 = view.totable();
datatable2
dataview view = basedt.defaultview; view.sort = "bfname"; dt2 = view.totable();
datatable3
dataview view = templatedt.defaultview; view.sort = "tfname"; dt3 = view.totable();
i need ensure 3 datatables contain same number of rows , same filenames in of 3 datatables.
how can this?
i know can write condition see (dt1.rows.count == dt2.rows.count == dt3.rows.count)
rows count how can check same file names in 3 datatables. filenames same extensions different.
if have 123.wmv
in datatable1, have 123.doc in second datatable , same 123 in third datatable either doc or docx extension. if have 5 rows in 1st datatable need ensure remaining datatables contain same 5 rows same filenames if not should show error message , stop execution of next lines of code.
you can use path.getfilenamewithoutextension
:
bool hassame(datatable w, datatable b, datatable t) { if((w.rows.count == b.rows.count && b.rows.count == t.rows.count) == false ) return false; (int = 0; < w.rows.count; i++) { var field1 = w.rows[i]["wfname"].tostring() ; var field2 = b.rows[i]["bfname"] .tostring() ; var field3 = t.rows[i]["tfname"].tostring() ; //if equal, uneccary getfilenamewithoutextension if(field1 == field2 && field2 == field3) continue; field1 = path.getfilenamewithoutextension(field1) ; field2 = path.getfilenamewithoutextension(field2) ; field3 = path.getfilenamewithoutextension(field3) ; if( (field1 == field2 && field2 == field3) == false) return false; } return true; }
the function assumes tables sorted, bit of pity. best if sorting done if rows same saving unnecessary action. need taking out datatable of function parameters class fields, thus, placing sorted table variable not in function variable scope - of course if need sort without comparison, if not, suggest more elegant code:
bool hassame(datatable w, datatable b, datatable t) { if((w.rows.count == b.rows.count && b.rows.count == t.rows.count) == false ) return false; var whashset = datatabletohashset (w, "wfname"); var bhashset = datatabletohashset (b, "bfname"); if(!whashset.setequals(bhashset)) return false; var thashset = datatabletohashset (t, "tfname"); return thashset.setequals(whashset); } hashset<string> datatabletohashset(datatable dt, string fieldname) { return new hashset<string>(dt.asenumerable().select (dr => path.getfilenamewithoutextension( dr[fieldname].tostring()) )); }
Comments
Post a Comment