I am attempting to get distinct values from a datatable column. here is my code..
var sourceItems = ds.Tables[0].AsEnumerable()
.GroupBy(x => x.Field<string>("Source").ToString())
.Select(x => x.First());
ddlSource.DataSource = sourceItems;
ddlSource.DataBind();
This code is returning 4 rows of System.Data.DataRow as the values. I need the actual values stored in the rows not the row type. Also is this code a proper way to grab only distinct values in the column?
I would do something like this:
Note that
.ToList()can be skipped, but of course it depends on what theDataSourceproperty of theddlSourceobject is able to accept. If It’s a winforms control I suspectToListis necessary.Your code does basically the same as this one, but you must change the last
SelectintoSelect(x => x.Key)to select the values that are used to group the rows, and not the first row.Also your code has more overhead than using
Distinct, sinceGroupBycreates subgroups of the original collection.