c# - Distinct all columns in a datatable and store to another datatable with LINQ -


i have datatable more 10 columns , distinct columns , store result datatable.

is there way distinct columns in datatable using linq without naming ones?

i've tried code below give 1 row. please give me advice case.

datatable dtpurchaseorder = new datatable(); datatable dt = new datatable(); dt.columns.add("ponumber"); dt.columns.add("customer"); dt.columns.add("address"); dt.rows.add("po123456", "mh", "123"); dt.rows.add("po123456", "mh", "123"); dt.rows.add("po654321", "ab", "123"); dt.rows.add("po654321", "ab", "123");  foreach (datarow r in dt.rows) {     var lstpo = (from row in dtpurchaseorder.asenumerable()                  select row.field<string>("ponumber")).count();     if (lstpo == 0)         dtpurchaseorder.rows.add(r.itemarray); }  dtpurchaseorder.acceptchanges(); 

solution 1:

simplest solution defaultview.totable.

dt.defaultview.totable(true, "ponumber", "customer", "address"); 

solution 2 :

another alternative using linq statement filter distinct rows , looping them required.

var result =  dt.asenumerable()             .select(row => new {                 ponumber = row.field<string>("ponumber"),                 customer = row.field<string>("customer"),                 address = row.field<string>("address")             }).distinct(); 

solution 3 :

traditional way of checking existence primarykey defined.

var ponum = dtpurchaseorder.columns.add("ponumber"); var cust = dtpurchaseorder.columns.add("customer"); var address = dtpurchaseorder.columns.add("address");   dtpurchaseorder.primarykey =  new[] {ponum, cust, address};  dt.rows.add("po123456", "mh", "123"); dt.rows.add("po654321", "ab", "123"); dt.rows.add("po654321", "ab", "123");    foreach (datarow r in dt.rows) {     var exisiting = dtpurchaseorder.rows.find(r.itemarray);      if (exisiting == null)       {         dtpurchaseorder.rows.add(r.itemarray);     }        }    

working sample


Comments

Popular posts from this blog

c# - Validate object ID from GET to POST -

node.js - Custom Model Validator SailsJS -

php - Find a regex to take part of Email -