Unique values in a Column to One column in DataTable using LINQ

Hi Friends,

I am having data from which I have to fetch all unique values from column “Product” and then i have to take all unique values in a 1 column Data Table. Hence, Data table will only have single column containing unique values of products.

I have written below LINQ and taken all unique values in a string array :–>

DataTbl.AsEnumerable.Select(Function(r) r(“Product”).ToString.Trim).Distinct.ToArray

But, may i know how can i take array values to 1 column data table further?


Instead of .ToArray use .CopyToDataTable…

Also you can use datatbl.defaultview.ToTable(True,"Product") will give you the distinct products as a datatable with only products column

This needs to be used in assign the output would be datatable

Hope this helps


I already tried this, datatbl.defaultview.ToTable(True,“Product”)
and its working perfect, but apart from that checking if there is any other approach.

1 Like


As mentioned above use .CopyToDataTable


Getting error :–>

How about the following?

dt1Col = DataTbl.AsEnumerable.GroupBy(Function(r) r("Product").ToString.Trim).Select(Function(g) dt1Col.LoadDataRow({g.First().Item("Product").ToString.Trim},False)).CopyToDataTable

Please create datatable which has single column : dt1col.


1 Like


Ahh my bad youc an try like this

(From A in Dt.AsEnumerable.Select(Function(r) r("Product").ToString.Trim).Distinct Select x=Dt.Rows.Add(A)).CopyToDatatable

If dt does not have single column then change the x=dt.Rows in this dt to another dt with one column


1 Like

So moral of the story is,
Whenever we want to add array elements to data table, we have to create blank data table with single column first.

Perfectly working :beers:, thank you.

1 Like

This topic was automatically closed 3 days after the last reply. New replies are no longer allowed.