I’ve got two classes (Course, Person). The students enrolled in a course are stored in a List(of Person) of the Course class. Now I want to use LINQ to query a List(of Course) to retrieve only courses in which a Person of a certain name (e.g. “Jane”) is enrolled.
How to write a LINQ query to achieve this?
The following query should illustrate my intention, but obviously it does not work that way.
In this simplified example, it would be an alternative to just store the person name in a list of Strings and use Contains() to check for a certain String in the list. – This is not an option in the real application.
Below is the full code for a working (except for the LINQ query) VB.Net console application that reproduces the scenario described above.
How to write a LINQ query to achieve this?
The following query should illustrate my intention, but obviously it does not work that way.
Code:
Dim selectedCourses As List(Of Course) =
(From sc As Course In AllCourses
Where sc.Students.Name = "Jane").ToList()
In this simplified example, it would be an alternative to just store the person name in a list of Strings and use Contains() to check for a certain String in the list. – This is not an option in the real application.
Below is the full code for a working (except for the LINQ query) VB.Net console application that reproduces the scenario described above.
Code:
Public Class Person
Public Property PersonName As String
End Class
Public Class Course
Public Property CourseName As String
Public Property Students As New List(Of Person)
Public Property Level As Integer
End Class
Module Module1
Sub Main()
Dim mike As New Person With {.PersonName = "Mike"}
Dim jane As New Person With {.PersonName = "Jane"}
Dim joe As New Person With {.PersonName = "Joe"}
Dim AllCourses As New List(Of Course)
Dim c As Course
c = New Course With {.CourseName = "Math", .Level = 2}
c.Students.AddRange({mike, jane})
AllCourses.Add(c)
c = New Course With {.CourseName = "Biology", .Level = 1}
c.Students.AddRange({mike, jane, joe})
AllCourses.Add(c)
c = New Course With {.CourseName = "Chemistry", .Level = 2}
c.Students.AddRange({mike, joe})
AllCourses.Add(c)
Dim selectedCourses As List(Of Course) =
(From sc As Course In AllCourses
Where sc.Students.Name = "Jane").ToList()
For Each c In selectedCourses
Console.WriteLine(c.CourseName)
Next
Console.WriteLine("Press ENTER to exit")
Console.ReadLine()
End Sub
End Module
Last edited: