LINQ with custom objects in C Sharp (C#) - Time & Space Complexity
When using LINQ with custom objects, it's important to understand how the time to run queries changes as the number of objects grows.
We want to know how the program's work increases when we have more items to search or filter.
Analyze the time complexity of the following code snippet.
var people = new List<Person> {
new Person("Alice", 30),
new Person("Bob", 25),
new Person("Charlie", 35)
};
var result = people.Where(p => p.Age > 28).ToList();
This code filters a list of custom Person objects to find those older than 28 years.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: The
Wheremethod loops through each Person object to check the age condition. - How many times: It runs once for every person in the list.
As the number of people increases, the program checks each one once.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 checks |
| 100 | 100 checks |
| 1000 | 1000 checks |
Pattern observation: The number of checks grows directly with the number of people.
Time Complexity: O(n)
This means the time to filter grows in a straight line as the list gets bigger.
[X] Wrong: "LINQ queries run instantly no matter how many items there are."
[OK] Correct: LINQ still checks each item one by one, so more items mean more work and more time.
Understanding how LINQ works with custom objects helps you explain how your code handles data efficiently, a useful skill in many coding discussions.
"What if we changed the filter to check two conditions instead of one? How would the time complexity change?"