Link to home
Start Free TrialLog in
Avatar of Nelson3000
Nelson3000Flag for United States of America

asked on

LINQ statement to find duplicates. Proper Syntax when: Option Strict On

I am performing a LINQ query to find duplicates in a DataTable.  It is working perfectly with Option Strict OFF.  However, for compliance purposes, I must have Option Strict ON.  Example-A is the original code.  In Example-B, I modified the syntax to get it to compile, but it fails at runtime.

Dim dtDivision4_Results As DataTable
<Fill DataTable>


Example-A: LINQ query when: Option Strict OFF

This code runs properly and returns duplicates in dtDupAccounts

 Dim dtDupAccounts = dtDivision4_Results.AsEnumerable().GroupBy(Function(i) i.Field(Of String)("AccountNumber")).Where(Function(g)
 g.Count() > 1).Select(Function(g) g.Key)


Example-B: LINQ query when: Option Strict ON

The code compiles, but at runtime, I get an "Invalid Cast Exception".

 Dim dtDupAccounts As DataTable = CType(dtDivision4_Results.AsEnumerable().GroupBy(Function(i) i.Field(Of String)
 ("AccountNumber")).Where(Function(g) g.Count() > 1).Select(Function(g) g.Key), DataTable)


The exact exception I get is:

+            $exception      {"Unable to cast object of type 'WhereSelectEnumerableIterator`2[System.Linq.IGrouping`2[System.String,System.Data.DataRow],System.String]' to type 'System.Data.DataTable'."}      System.InvalidCastException


Please help me perfect the syntax of the query in Example-B.
I am a novice to VB.Net and your help in correcting my syntax would be greatly appreciated.
ASKER CERTIFIED SOLUTION
Avatar of Fernando Soto
Fernando Soto
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of Nelson3000

ASKER

Fernando to the rescue, once again!
Your solution worked perfectly.
Thanks very much for the EXPERT solution and the explanation.
Not a problem Nelson; glad to help.