Nelson3000
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.AsEnum erable().G roupBy(Fun ction(i) i.Field(Of String)("AccountNumber")). Where(Func tion(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. AsEnumerab le().Group By(Functio n(i) i.Field(Of String)
("AccountNumber")).Where(F unction(g) g.Count() > 1).Select(Function(g) g.Key), DataTable)
The exact exception I get is:
+ $exception {"Unable to cast object of type 'WhereSelectEnumerableIter ator`2[Sys tem.Linq.I Grouping`2 [System.St ring,Syste m.Data.Dat aRow],Syst em.String] ' to type 'System.Data.DataTable'."} System.InvalidCastExceptio n
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.
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.AsEnum
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.
("AccountNumber")).Where(F
The exact exception I get is:
+ $exception {"Unable to cast object of type 'WhereSelectEnumerableIter
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
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Not a problem Nelson; glad to help.
ASKER
Your solution worked perfectly.
Thanks very much for the EXPERT solution and the explanation.