c# - using distinct in DataTable.Select function -
i have data table , want populate 2 datatables using datatable,here simple form of table
my data table columns [name][family][id][propertyid][propertyenergy] john smith 1 12 gas john smith 1 13 gas john smith 1 14 null john smith 1 15 gas hannah smith 2 16 gas hannah smith 2 17 gas hannah smith 2 18 gas
i want use query in datatable select distinct [name][family][id] table
results
john smith 1 hannah smith 2
and again use query in datatable select [id][propertyid][propertyenergy] table
results
1 12 gas 1 13 gas 1 14 null 1 15 gas 2 16 gas 2 17 gas 2 18 gas
i searched , found can datatable.select
examples have seen shows can add sentense datatable.select
, have no idea how perform things distinct
in it, can please me or give me hints how it? thank much
i'd use linq-to-datatable
instead:
var distinctnames = table.asenumerable() .select(row => new { name = row.field<string>("name"), family = row.field<string>("family"), id = row.field<int>("id") }) .distinct(); var distinctproperties = table.asenumerable() .select(row => new { id = row.field<int>("id"), propertyid = row.field<int>("propertyid"), propertyenergy = row.field<int>("propertyenergy") }) .distinct();
if need 2 additional datatables
have create , fill them manually since columns different main-table. can fill them in loop queries above.
this should work is:
string[] namecolumns = { "name", "family", "id" }; datatable tblnames = table.clone(); var removecolumns = tblnames.columns.cast<datacolumn>() .where(c => !namecolumns.contains(c.columnname)).tolist(); removecolumns.foreach(c => tblnames.columns.remove(c)); foreach (var x in distinctnames) tblnames.rows.add(x.name, x.family, x.id); string[] propertycolumns = { "id", "propertyid", "propertyenergy" }; datatable tblproperties = table.clone(); removecolumns = tblproperties.columns.cast<datacolumn>() .where(c => !propertycolumns.contains(c.columnname)).tolist(); removecolumns.foreach(c => tblproperties.columns.remove(c)); foreach (var x in distinctproperties) tblproperties.rows.add(x.id, x.propertyid, x.propertyenergy);
Comments
Post a Comment