LINQ Quiz
Posted by Peet Brits on November 1, 2008
Just for fun, I made a little quiz following my previous LINQ article.
Question 1
What is the difference in effect of the following code sections? Note that “Failed” is a nullable bit, so we will label the states as red, green and yellow (null).
// Option A
where (filter.Failed.HasValue && doc.Failed.HasValue ? filter.Failed == doc.Failed : true)
// && (…) — more filters here
// Option B
where (filter.Failed.HasValue ? filter.Failed == doc.Failed : true)
// && (…) — more filters here
Question 2
What would happen if all the queries ended with “false”?
where (… ? … : false) && (… ? … : false)
Question 3
Keeping both performance and readability in mind, what is the difference between grouping all the queries together (see option A), against having each in a separate section (see option B)?
// Option A
docs = from doc in docs
where (filter.Failed.HasValue ? filter.Failed == doc.Failed : true)
// && (…) — more filters here
select doc;
// Option B
if (filter.Failed.HasValue)
docs = from doc in docs
where filter.Failed == doc.Failed
select doc;
// more filter blocks here
Peet Brits said
Hmm, seems like I’m not going to get any replies…
Peet Brits said
For what it’s worth, here’s my take on things:
1) “A” returns colour (red/green) and yellow, “B” returns only red/green.
2) Will only work if the filter conditions are not empty.
3) Regarding performance, LINQ queries are only executed once when needed, not while building the iterator, thus the difference is not significant. I believe this is build upon the C# 3.0 enumeration technology, thanks to keywords like “yield return”. Regarding readability, use “A” for simple query conditions, but “B” for more complex ones.