0
0
C Sharp (C#)programming~5 mins

Lambda expression syntax in C Sharp (C#) - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Lambda expression syntax
O(n)
Understanding Time Complexity

We want to understand how the time it takes to run code with lambda expressions changes as the input grows.

Specifically, how does using a lambda affect the number of steps the program takes?

Scenario Under Consideration

Analyze the time complexity of the following code snippet.


var numbers = new List<int> {1, 2, 3, 4, 5};
var squares = numbers.Select(x => x * x).ToList();

This code creates a list of numbers and uses a lambda expression to create a new list of their squares.

Identify Repeating Operations

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: The lambda runs once for each number in the list.
  • How many times: Exactly as many times as there are items in the list.
How Execution Grows With Input

Each number causes one multiplication operation inside the lambda.

Input Size (n)Approx. Operations
1010 multiplications
100100 multiplications
10001000 multiplications

Pattern observation: The number of operations grows directly with the number of items.

Final Time Complexity

Time Complexity: O(n)

This means the time to run grows in a straight line as the list gets bigger.

Common Mistake

[X] Wrong: "Using a lambda makes the code run slower in a way that changes the time complexity."

[OK] Correct: The lambda is just a short way to write a function. It runs once per item, so it does not add extra loops or steps beyond the list size.

Interview Connect

Understanding how lambdas work with collections helps you explain code efficiency clearly and confidently in interviews.

Self-Check

"What if the lambda expression called another method that itself loops over the list? How would the time complexity change?"