Bird
Raised Fist0
C Sharp (C#)programming~10 mins

LINQ with custom objects in C Sharp (C#) - Step-by-Step Execution

Choose your learning style10 modes available

Start learning this pattern below

Jump into concepts and practice - no test required

or
Recommended
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
Concept Flow - LINQ with custom objects
Create list of objects
Write LINQ query
Evaluate query: filter/map
Iterate results
Output filtered/mapped objects
Start with a list of custom objects, write a LINQ query to filter or select, then iterate and output the results.
Execution Sample
C Sharp (C#)
var people = new List<Person> {
  new Person("Alice", 30),
  new Person("Bob", 20),
  new Person("Charlie", 25)
};
var adults = people.Where(p => p.Age >= 21);
foreach(var adult in adults) Console.WriteLine(adult.Name);
This code filters a list of Person objects to find those aged 21 or older and prints their names.
Execution Table
StepActionEvaluationResult
1Create list 'people'List contains 3 Person objectspeople = [Alice(30), Bob(20), Charlie(25)]
2Apply Where filter p.Age >= 21Check Alice: 30 >= 21True, include Alice
3Apply Where filter p.Age >= 21Check Bob: 20 >= 21False, exclude Bob
4Apply Where filter p.Age >= 21Check Charlie: 25 >= 21True, include Charlie
5Iterate filtered resultsFirst: AliceOutput: Alice
6Iterate filtered resultsSecond: CharlieOutput: Charlie
7No more itemsIteration endsLoop exits
💡 All people checked; only those 21 or older included; iteration ends after last item.
Variable Tracker
VariableStartAfter Step 1After Step 4After Step 7
peopleempty[Alice(30), Bob(20), Charlie(25)][Alice(30), Bob(20), Charlie(25)][Alice(30), Bob(20), Charlie(25)]
adultsnulldeferred query[Alice(30), Charlie(25)] (filtered)[Alice(30), Charlie(25)] (filtered)
Key Moments - 2 Insights
Why does 'adults' not immediately contain filtered results after Step 2?
LINQ uses deferred execution, so 'adults' holds the query but does not run it until iteration (see Steps 5-7).
Why is Bob excluded from the output even though he is in the original list?
Because Bob's age (20) does not satisfy the filter condition p.Age >= 21 (see Steps 3 and 4).
Visual Quiz - 3 Questions
Test your understanding
Look at the execution table, what is the result of evaluating Bob's age in Step 3?
ATrue, include Bob
BFalse, exclude Bob
CError, Bob missing age
DTrue, but exclude Bob
💡 Hint
Check Step 3 in the execution_table where Bob's age is compared to 21.
At which step does the program start outputting names?
AStep 5
BStep 4
CStep 2
DStep 7
💡 Hint
Look at the iteration steps in the execution_table where output happens.
If we change the filter to p.Age >= 20, how would the filtered list change?
AOnly Alice included
BAlice and Charlie included
CAlice, Bob, and Charlie included
DOnly Bob included
💡 Hint
Refer to variable_tracker and consider ages of all people compared to 20.
Concept Snapshot
LINQ with custom objects:
- Create a list of objects
- Use LINQ methods like Where to filter
- LINQ queries use deferred execution
- Iterate query results to get filtered objects
- Access object properties in lambda conditions
Full Transcript
This example shows how to use LINQ with a list of custom Person objects. First, we create a list with three people: Alice (30), Bob (20), and Charlie (25). Then, we write a LINQ query using Where to select only those with Age 21 or older. The query is not run immediately but waits until we iterate over it. When we loop through the filtered results, we print the names of Alice and Charlie because Bob does not meet the age condition. This demonstrates deferred execution and filtering with LINQ on custom objects.

Practice

(1/5)
1. What does LINQ primarily help you do with custom objects in C#?
easy
A. Create new classes automatically
B. Compile code faster
C. Filter, sort, and select data easily
D. Manage memory manually

Solution

  1. Step 1: Understand LINQ's purpose

    LINQ is designed to query collections like lists of objects easily.
  2. Step 2: Identify LINQ's main features

    It helps filter, sort, and select data without manual loops.
  3. Final Answer:

    Filter, sort, and select data easily -> Option C
  4. Quick Check:

    LINQ = Filter, sort, select [OK]
Hint: Remember LINQ is for querying data collections [OK]
Common Mistakes:
  • Thinking LINQ creates classes
  • Confusing LINQ with compilation
  • Assuming LINQ manages memory
2. Which of the following is the correct syntax to select all names from a list of Person objects using LINQ?
easy
A. var names = people.Select(p => p.Name());
B. var names = people.Select(p.Name);
C. var names = people.Select(p => p);
D. var names = people.Select(p => p.Name);

Solution

  1. Step 1: Understand Select syntax

    Select expects a lambda expression to pick a property, like p => p.Name.
  2. Step 2: Check each option

    var names = people.Select(p => p.Name); uses correct lambda syntax. var names = people.Select(p.Name); misses lambda. var names = people.Select(p => p); selects whole object. var names = people.Select(p => p.Name()); wrongly calls Name as method.
  3. Final Answer:

    var names = people.Select(p => p.Name); -> Option D
  4. Quick Check:

    Select needs lambda with property [OK]
Hint: Use lambda syntax p => p.Property for Select [OK]
Common Mistakes:
  • Omitting lambda arrow =>
  • Calling property as method
  • Selecting whole object instead of property
3. Given the class Person { public string Name; public int Age; } and list people with three persons: Alice(30), Bob(25), and Carol(35), what does this LINQ query return?
var result = people.Where(p => p.Age > 28).Select(p => p.Name).ToList();
medium
A. ["Alice", "Carol"]
B. ["Bob"]
C. ["Alice", "Bob", "Carol"]
D. Empty list

Solution

  1. Step 1: Filter people older than 28

    Alice is 30 (yes), Bob is 25 (no), Carol is 35 (yes).
  2. Step 2: Select their names

    Names selected are "Alice" and "Carol".
  3. Final Answer:

    ["Alice", "Carol"] -> Option A
  4. Quick Check:

    Age > 28 filters Alice and Carol [OK]
Hint: Filter first, then select property [OK]
Common Mistakes:
  • Including Bob who is younger
  • Selecting whole object instead of names
  • Confusing > with <
4. What is wrong with this LINQ query?
var adults = people.Where(p => p.Age >= 18).Select(p => p.Name);
foreach(var name in adults) Console.WriteLine(name);
medium
A. The query is correct and will print all names of adults
B. The lambda expression syntax is incorrect
C. The query is missing ToList() or ToArray(), so it won't compile
D. The Where clause should be after Select

Solution

  1. Step 1: Check LINQ query syntax

    Where and Select are used correctly with proper lambda syntax.
  2. Step 2: Check foreach usage

    LINQ returns IEnumerable<string>, which foreach can iterate without ToList().
  3. Final Answer:

    The query is correct and will print all names of adults -> Option A
  4. Quick Check:

    IEnumerable works with foreach directly [OK]
Hint: IEnumerable can be iterated without ToList() [OK]
Common Mistakes:
  • Thinking ToList() is mandatory before foreach
  • Misplacing Where and Select order
  • Incorrect lambda syntax
5. You have a list of Product objects with properties Name (string) and Price (decimal). How do you create a dictionary with product names as keys and prices as values, but only include products costing more than 50 using LINQ?
hard
A. products.ToDictionary(p => p.Name, p => p.Price).Where(p => p.Value > 50);
B. products.Where(p => p.Price > 50).ToDictionary(p => p.Name, p => p.Price);
C. products.Select(p => new {p.Name, p.Price > 50}).ToDictionary(p => p.Name, p => p.Price);
D. products.Where(p => p.Price > 50).Select(p => p.Name).ToDictionary();

Solution

  1. Step 1: Filter products with price > 50

    Use Where to keep only products costing more than 50.
  2. Step 2: Convert filtered list to dictionary

    Use ToDictionary with key selector p.Name and value selector p.Price.
  3. Final Answer:

    products.Where(p => p.Price > 50).ToDictionary(p => p.Name, p => p.Price); -> Option B
  4. Quick Check:

    Filter then ToDictionary with key and value selectors [OK]
Hint: Filter first, then use ToDictionary with key and value [OK]
Common Mistakes:
  • Trying to filter after ToDictionary (invalid)
  • Selecting anonymous types instead of original objects
  • Calling ToDictionary without key/value selectors