c# - How can I select distinct column combinations from a DataTable object with another column as a condition? -


i'm using c# 2010.

i have datatable object i'm working has following structure (and filled sample data):

"name"    "id"    "hiredate"    "termdate" bobby     1        5/1/2011       7/1/2011 peggy     2        5/1/2011 jenny     3        5/2/2011 jenny     3        5/2/2013 jenny     3        5/2/2011       6/1/2011 peggy     2        5/1/2011 

i want filter datatable keep distinct ("id","hiredate") combinations. furthermore, can see, not has "termdate" value. when deciding distinct ("id","hiredate") combination keep, want keep 1 has "termdate". if there's no "termdate" in of them doesn't matter 1 discarded.

so resulting table after doing be:

"name"    "id"    "hiredate"    "termdate" bobby     1        5/1/2011       7/1/2011 peggy     2        5/1/2011 jenny     3        5/2/2013 jenny     3        5/2/2011       6/1/2011 

jenny has 2 entries because appeared 2 different "hiredate" values, , 1 of them duplicated - entry without "termdate" removed.

any suggestions how in c#? again, i'm using datatable object. still need keep "name" , "termdate" fields - if didn't, able distinct ("id","hiredate") list, need retained.

thanks help!

i this, dt original datatable -

this should cover eventualities due ordering of data view, date list maintained allows addition of multiple hire dates user.

            dataview dv = new dataview(dt);             dv.sort = "id asc, hiredate desc, termdate desc";              string lastid = "0";             list<datetime> addedhiredatesforuser = new list<datetime>();              foreach (datarowview drv in dv)             {                 if (drv["id"].tostring() != lastid)                 {                     addedhiredatesforuser = new list<datetime>();                     addedhiredatesforuser.add(datetime.parse(drv["hiredate"].tostring()));                      // next id, add row new datatable                 }                 else if (!addedhiredatesforuser.contains(datetime.parse(drv["hiredate"].tostring())))                 {                     addedhiredatesforuser.add(datetime.parse(drv["hiredate"].tostring());                      // next date, add row new datatable                 }                  lastid = drv["id"].tostring();             } 

Comments

Popular posts from this blog

c++ - CryptStringToBinary API behavior -

c++ - Correct method for redrawing a layered window -

java.util.scanner - How to read and add only numbers to array from a text file -