LINQ query syntax in C Sharp (C#) - Time & Space Complexity
We want to understand how the time it takes to run a LINQ query changes as the data size grows.
How does the number of items affect the work done by the query?
Analyze the time complexity of the following code snippet.
var numbers = new List {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
var evenNumbers = from num in numbers
where num % 2 == 0
select num;
foreach (var even in evenNumbers)
{
Console.WriteLine(even);
}
This code selects all even numbers from a list and prints them.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Checking each number in the list to see if it is even.
- How many times: Once for every item in the list.
As the list gets bigger, the query checks more numbers one by one.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 checks |
| 100 | 100 checks |
| 1000 | 1000 checks |
Pattern observation: The work grows directly with the number of items.
Time Complexity: O(n)
This means the time to run the query grows in a straight line as the list gets bigger.
[X] Wrong: "LINQ queries always run instantly regardless of data size."
[OK] Correct: LINQ still checks each item one by one, so bigger lists take more time.
Understanding how LINQ processes data helps you write efficient queries and explain your code clearly in interviews.
"What if we added another where condition to filter numbers greater than 5? How would the time complexity change?"