问题
I need to select distinct records from a data table using linq and C# and I can't seem to get the syntax correct. I have the following code, which returns all the rows in a data table, how do I just return DISTINCT rows?
DataTable dt = ds.Tables[0];
var q = from dr in dt.AsEnumerable() select dr;
回答1:
You'll need to use DataRowComparer
IEnumerable<DataRow> distinctRows =
dt.AsEnumerable().Distinct(DataRowComparer.Default);
More info on comparing data rows using linq to dataset can be found here
回答2:
We could have:
var q = (from dr in dt.AsEnumerable() select dr).Distinct(DataRowComparer.Default);
But really, the from x in ... select x
is redundant, so we can have:
var q = dt.AsEnumerable().Distinct(DataRowComparer.Default);
But all AsEnumerable()
will do most of the time, is either nothing (if it's already as such) or potentially slow things up (if distinct could be processed better elsewhere), so it's normally better to do:
var q = dt.Distinct(DataRowComparer.Default);
Though there are cases where the former beats the latter.
回答3:
(from dr in dt.AsEnumerable() select dr).Distinct();
来源:https://stackoverflow.com/questions/8853390/select-distinct-from-datatable-using-linq-and-c-sharp