views:

170

answers:

3

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.

A: 

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")) 
Aaronontheweb
got same error when execute your query
James123
Ah shit I should have paid more attention to the error message. I've got it now. Your problem isn't your SQL syntax - it's the datatype you expect since you're marking it as an Enumerable collection of DataRows when you're projecting tuples which contain a pair of strings.
Aaronontheweb
Change the syntax so you're projecting a new DataRow with each of the strings added as columns - either that or strip the As IEnumerable(Of DataRow) and just accept the implict type as a result.
Aaronontheweb
Still an error ... at same place
James123
A: 

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

Johnny
You're missing a curly brace at the front of your LINQ projection, but I get your meaning.
Aaronontheweb
This one is not returing distinct columns
James123
A: 

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
Johnny
How to user 'query' objects. I mean How to iterate that?
James123