views:

41

answers:

2
return (from s in db.StudentMarks
                where s.Class == Class && s.Year == Year // this line
                orderby s.Year, s.ExamType
                select new StudentAddMarks()
                {
                    --Obj
                 }).ToList();

I am going to return an Object depending on the Class and Year params. I want to remove the where condition when the Class and Year parames are null or zero.

Any ideas please.

+1  A: 

This should work:

where (s.Class == Class && s.Year == Year) || Class == null || 
       Class == 0 || Year == null || Year == 0
jball
I dont want to execute the where condition if the vlaues are 0
Aditya
Any or all of the values? Is `null` not a concern?
jball
Thanks a lot I got the concept and answer. I appreciaet your help
Aditya
+3  A: 

Just add a clause handling null or zero values as well:

where ((Class != null && Class != 0) ? s.Class == Class : true) &&
      ((Year  != null && Year  != 0) ? s.Year  == Year  : true)

The above code uses the shorthand if-then-else syntax, that works as follows:

value = (condition ? if_true : if_false);
// ...is equivalent to...
if (condition)
{
    value = if_true;
}
else 
{
    value = if_false;
}
Tomas Lycken
upvote for a good explanation
jball
Thanks a lot Your Answer helped me a lot. result = (from p in GetAllStudentMarksList() where (collection.SearchClass != null ? p.Class == collection.SearchClass : true)
Aditya