get distinct rows from datatable using Linq (distinct with mulitiple columns)

谁说胖子不能爱 提交于 2020-01-03 12:29:12

问题


I am trying to distinct on multiple columns and get datarows from datatable. but getting error.

 Dim query As IEnumerable(Of DataRow) = 
            (From row As DataRow In SourceTable.AsEnumerable() _
             Select row.Field(Of String)("ColumnName1"),
                    row.Field(Of String)("ColumnName2") ).Distinct()

below error:

Unable to cast object of type '<DistinctIterator>d__7a`1[System.String]' 
to type 'System.Collections.Generic.IEnumerable`1[System.Data.DataRow]'.

I want another datatable with distinct row based on given columns from SourceTable.


回答1:


Try This one then

Dim query = From q In (From p In dt.AsEnumerable() Select New With {.col1= p("ColumnName1"), .col2 = p("ColumnName2")}) Select q.col1, q.col2 Distinct



回答2:


Try this (a bit of a guess on my part):

Dim query As IEnumerable(Of DataRow) =  
        (From row As DataRow In SourceTable.AsEnumerable().Distinct()  _ 
         Select row.Field(Of String)("ColumnName1"), 
                row.Field(Of String)("ColumnName2")) 



回答3:


Try this

var distinctRows = (from DataRow dRow in dTable.Rows
                    select new col1=dRow["dataColumn1"],col2=dRow["dataColumn2"]}).Distinct();

this is in C#. Convert it into vb.net



来源:https://stackoverflow.com/questions/3234341/get-distinct-rows-from-datatable-using-linq-distinct-with-mulitiple-columns

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