Practice mode C#

What does this print: var list = new List { 1, 2, 3 }; var q = list.Where(x => x > 1); list.Add(4); Console.WriteLine(q.Count());?

Correct answer B. 3

Explanation

LINQ queries such as Where use deferred execution: the variable q stores the query, not its results. The filter runs only when q is enumerated, here by Count(). By then the list contains 1, 2, 3 and 4, so three elements (2, 3, 4) satisfy x > 1. Calling ToList() before the Add would have captured the result 2.

Report a problem

Answer checked How we write and check questions

Tip: press A, B, C or D to answer, and N for the next question.

Advertisement

Have a question about this answer?

Your email address will not be published. Required fields are marked *

Links and website addresses are not allowed in comments.