I have the following class created:
Public Class Candidate
Public Account As String
Public StartDate As Date
Public EndDate As Date
End Class
Now, in a second class, I want to take a List(Of Candidate) and group it by matching start and end dates. I have the following code:
Public Class MyClass
Private _Candidates As New List(Of Candidate)
Private _Grouped_Candidates as ????????
Sub Group_Candidiates()
_Grouped_Candidates = From Candidate In _Candidates
Group Candidate By StrtDt = Candidate.StartDate, EndDt = Candidate.EndDate Into Group
Select New With {.Grp = Group, .StrtDt = StrtDt, .EndDt = EndDt}
End Sub
End Class
And then at a different part of this class, I want to perform an operation on this in-memory query:
Sub DoStuff()
For Each Grp In _Grouped_Candidates
DoSometihng(Grp.Grp.Select(Function(Candidate) Candidate.Account).ToList, _
Grp.StrtDt, _
Grp.EndDt)
Next
End Sub
This is giving me an error because I don’t have _Grouped_Candidates declared correctly.
My question is if this is bad programming practice (Keeping an in-memory query saved beyond the scope of a sub) and, if so, what should be done instead.
And, if not, how can I declare the query correctly so I can use it throughout my class?
Thanks!!!
Anonymous types were designed specifically to be used within the scope of a single method. While there are means of using them across methods, they’re messy, generally bad practice, and on the whole much more work than they’re worth. The easiest solution is to create a new named type that has properties representing what your current anonymous type uses, and to then use that named type. Whoever is responsible for maintaining the code will thank you for putting in the tiny up-front time instead of using messy hacks.