LINQ to DataTable, finding duplicate rows
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 { column开发者_StackOverflow1 = 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?
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
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") }
I'm not sure about query syntax with VB.NET by try this
Dim q = d.AsEnumerable().Select(Function(r) New With { .Column1 = r("Product"), .Column2 = r("Value")}) _
.GroupBy(Function(r) New With {r.Column1, r.Column2}) _
.Where(Function(g) g.Count() >1 )
For Each item In q
Console.WriteLine(item.Key)
Next
精彩评论