I need to filter my records on the basis of "courseId" which is passed as parameter -
Here is my code -
public IEnumerable<string> GetStudentIdsByRoleAndCourse(string role, string courseId = null)
{
var query = (from item in Data.TableForQuery<MasterTable>()
where item.RoleId == role
select item).ToList();
if (courseId != null)
{
return (from item in query
let student = Students.GetModelById(item.StudentId)
where student.DisplayInReports && student.CourseId == courseId
orderby student.Name
select student.Id).ToList();
}
return (from item in query
let student = Students.GetModelById(item.StudentId)
where student.DisplayInReports
orderby student.Name
select student.Id).ToList();
}
Because I was not convinced with writing separate return statements -
I have now modified the code as below - to cater for the nullable parameter courseId
public IEnumerable<string> GetStudentIdsByRoleAndCourse(string role, string courseId = null)
{
var query = (from item in Data.TableForQuery<MasterTable>()
where item.RoleId == role
select item).ToList();
return (from item in query
let student = Students.GetModelById(item.StudentId)
where student.DisplayInReports
&& (courseId == null || student.CourseId == courseId)
orderby student.Name
select student.Id).ToList();
}
Wondering if there is even better way than above to achieve same.
Thanks a lot!
courseId
has a value or isnull
, in both cases&& student.CourseId == courseId
will cover it. So, the extracourseId == null ||
is not needed. You can verify that yourself. Also, you should consider usingjoin
to joinMasterTable
with theStudents
to get the results in one query, this would saves the round-trip, and reduces the memory allocation (it will only store the results in the memory). \$\endgroup\$student.CourseId
is not nullable. In that case, you could revise it tostudent.CourseId == courseId ?? student.CourseId
. \$\endgroup\$courseId
andRoleId
andstudent.Id
shouldn't bestring
s, they should beint
s orguid
s. \$\endgroup\$