I think the example you're trying doesn't work because it's returning an IEnumerable<Student>
and your method is supposed to return a List<Student>
;
You're also missing some parenthesis needed to group your &&
clauses together, so they're separated by the ||
operator.
One way to solve this would be to change the return type of your method to IEnumerable<Student>
, and to add some parenthesis around your &&
clauses:
public IEnumerable<Student> GetStudentBySelectedLecturer(List<Student> linkedList,
string text)
{
var lecturerInformation = text.Split(' ');
return from stud in linkedList
where (stud.LecturerFirstName == lecturerInformation[0] &&
stud.LecturerLastName == lecturerInformation[1]) ||
(stud.LecturerFirstName == lecturerInformation[1] &&
stud.LecturerLastName == lecturerInformation[0])
select stud;
}
Another way would be to cast the return value to a List<Student>
:
public List<Student> GetStudentBySelectedLecturer(List<Student> linkedList,
string text)
{
var lecturerInformation = text.Split(' ');
return (from stud in linkedList
where (stud.LecturerFirstName == lecturerInformation[0] &&
stud.LecturerLastName == lecturerInformation[1]) ||
(stud.LecturerFirstName == lecturerInformation[1] &&
stud.LecturerLastName == lecturerInformation[0])
select stud).ToList();
}
Of course there are still some potential problems, like if either linkedList
or lecturer
is null
, or if there is no space in text
(you would get an IndexOutOfRangeException
when trying to access index 1
). Also, you can use the Contains
method on the array of lecturer names to simplify your where
condition:
You could address these by doing something like:
public IEnumerable<Student> GetStudentBySelectedLecturer(List<Student> students,
string lecturer)
{
if (students == null || lecturer == null) return null;
var lecturerName = lecturer.Split(' ');
return from student in students
where lecturerName.Contains(student.LecturerFirstName) &&
lecturerName.Contains(student.LecturerLastName)
select student;
}