LINQ to DataTable, finding duplicate rows

11,726

Solution 1

Try this

Dim duplicates = d.AsEnumerable().GroupBy(Function(i) i.Field(Of String)("Product")).Where(Function(g) g.Count() > 1).Select(Function(g) g.Key)

For Each dup In duplicates
Next

Solution 2

Just try

Dim q = From row in d.AsEnumerable()
        Group row By row.Field(Of String)("Product")
        Into grp
        Where grp.Count() > 1
        Select { Country = row("Product"), Value = row("Value") }
Share:
11,726
Dan Champagne
Author by

Dan Champagne

Lead agile developer with a proven history of designing, building, and implementing small- and large-scale web and automation applications, workflow management applications, and data processing solutions, utilizing a variety of database technologies. Comfortable working independently or on a team. Extensive experience with open source technology, third-party APIs, RESTful web applications, and the full Microsoft stack. 15+ years with: NET (C#, VB, Framework 2.0 - 4.8, Core 1.0 - 3.0), SQL/T-SQL, C/C++, Test Driven Development 10+ years with: ASP.NET/MVC, XML/JSON, HTML5, CSS, SSIS/ETL, WPF, WCF 6+ years with: Agile Development, MySql, MongoDB, NoSql, JavaScript, Bootstrap API, JQuery, Ajax 2+ years with: Python, R, Java 1+ years with: Kotlin, React, React Native

Updated on June 04, 2022

Comments

  • Dan Champagne
    Dan Champagne almost 2 years

    Using the following DataTable:

        Dim d As New DataTable()
        d.Columns.Add("Product", GetType(System.String))
        d.Columns.Add("Value", GetType(System.Double))
    
        d.Rows.Add(New Object() {"OAP1", 100.0})
        d.Rows.Add(New Object() {"EPP4", 100})
        d.Rows.Add(New Object() {"OAP1", 150.25})
        d.Rows.Add(New Object() {"OAPIN", 200.0})
    

    I'm trying to use LINQ to identify if there are more than one of any type of product. In SQL, this would work something like:

    SELECT Product FROM SOME_TABLE HAVING COUNT(*) > 1
    

    I can't for the life of me work out how to do this in LINQ. I was following someone who did something like this:

        Dim q = From row In d.AsEnumerable()
                Group row By New { column1 = row("Product"), column2 = row("Value") }
                Into grp
                Where grp.Count() > 1
                Select row
    
        For Each item In q
            ' 'q' is not declared. It may be inaccessible due to its protection level.
        Next
    

    But I get an error when I try to actually use 'q'. Any ideas on how I can make this work?