Link to home
Start Free TrialLog in
Avatar of Thomas PAIK
Thomas PAIK

asked on

Remove rows in a datatable having duplicate column values using LINQ vb.net

Hi, I would like to remove rows in a datatable having duplicate column2 values (keep 1 only) using LINQ vb.net.

[DataTable_in]
column1 column2 column3
AAA 1 123
BBB 1 456
CCC 2 456

[DataTable_out]
column1 column2 column3
AAA 1 123
CCC 2 456

[Here provided is a pseudo code]
DataTable_out = DataTable_in.Distinct(column2).CopyToDataTable()

Please kindly provide a single-line LINQ vb.net code.
Avatar of David H.H.Lee
David H.H.Lee
Flag of Malaysia image

Hi, I would like to remove rows in a datatable having duplicate column2 values (keep 1 only) using LINQ vb.net.

Try this:

With LINQ
DataTable dt2 = ((from r in dt.AsEnumerable() 
select r["Column2"]).Distinct(DataRowComparer.Default)).CopyToDataTable();

Open in new window

OR

Without LINQ
DataTable dt2 = dt.DefaultView.ToTable(true, "Column2");

Open in new window

Note: dt is your original data table

Avatar of Thomas PAIK
Thomas PAIK

ASKER

Kindly provide your solution in vb.net code please.

DataTable_out should also be a 2 rows by 3 column datatable.
ASKER CERTIFIED SOLUTION
Avatar of David H.H.Lee
David H.H.Lee
Flag of Malaysia image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial