LINQ Select Distinct From Datatable

jsurpless

Well-known member
Joined
Jul 29, 2008
Messages
144
Programming Experience
Beginner
I'm trying to run a DISTINCT query to return a unique listing from my datatable...

VB.NET:
Dim Compound_Blocks_Table_Query = From Compound_Block_Record In Compound_Blocks_Table.AsEnumerable Select Compound_Block_Record
                                              Order By Compound_Block_Record.Field(Of String)("Compound.Block")

I've tried putting .Distinct after the Compound_Block_Record, as another line on the order of From & Order... no go...

What am I doing wrong?

Thanks!
 
You are selecting distinct DataRows, not rows with distinct values. No two DataRows in the DataTable are the same object so they are all distinct. Two DataRows that contain the same data are still two distinct objects. What you need to do is select the field values themselves, not the rows that contain them.
 
You are selecting distinct DataRows, not rows with distinct values. No two DataRows in the DataTable are the same object so they are all distinct. Two DataRows that contain the same data are still two distinct objects. What you need to do is select the field values themselves, not the rows that contain them.

Ok, thanks for clarifying that... just not clear on how I'd select distinct fields?
 
With your 'Select' clause. If you want to select the fields of the DataRow rather than the DataRow then that's what you have to specify in the 'Select' clause. Note that that will give you instances of an anonymous type.

If you want to stick to using DataRows then you will need to define your own IEqualityComparer that will compare the fields you want. You can then call the Distinct method and pass an instance of your type.
 
Back
Top