Select Distinct from DataTable using Linq and C#

和自甴很熟 提交于 2019-12-24 13:20:46

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!