The question's title isn't super clear, but I had a hard time formulating it any better. I'll show an example of what I am trying to do.
Function foo(id As Integer) As List(Of Version)
Dim listOfVersions as List(Of Version) = New List(Of Version)
For each version In MasterListOfVersions
For each object In version.ListOfObjects
If object.idObject = id Then listOfVersions.Add(version)
Next
Next
Return listOfVersions
End Function
This works, but I am trying to turn that into a lambda expression. So far, I have this down:
Return MasterListOfVersions.Select(Function(version) version.ListOfObjects.Where( _
Function(object) object.idObject = id)).ToList()
But it isn't quite right... I get the following error message:
List(Of IEnumerable(Of Object)) cannot be converted to List(Of Version)
I feel like I'm pretty close to the answer, but I've looked for a while and it seems like I'm stuck. Any help would be appreciated.
Basically you don't need to call Select
at all - you're only performing a filtering operation, which is what Where
gives you. You're not trying to transform the list. So just use:
Return MasterListOfVersions.Where_
(Function(version) version.ListOfObjects.Any_
(Function object) object.id = id)).ToList()
In other words, return all the versions where any of the objects within that version has the specified ID. Note that unlike your original code, this will only add each element of MasterListOfVersions
once, even its ListOfObjects
has multiple entries with the matching ID. I suspect this is what you want, to be honest.
Note that in your original code, you're using object.idObject
in one place but object.id
in another. It's not obvious which is correct.
See more on this question at Stackoverflow