Bird
Raised Fist0

Given List<object> mixed = new() { 5, "text", 7, 3.14, 10 };, which code snippet correctly creates a list of only the integers using pattern matching?

hard🚀 Application Q8 of Q15
C Sharp (C#) - Polymorphism and Abstract Classes
Given List<object> mixed = new() { 5, "text", 7, 3.14, 10 };, which code snippet correctly creates a list of only the integers using pattern matching?
Avar ints = mixed.Where(item => item is int i).Select(item => (int)item).ToList();
Bvar ints = mixed.Where(item => item is int i).Select(i => i).ToList();
Cvar ints = mixed.OfType<int>().ToList();
Dvar ints = mixed.Select(item => item as int).ToList();
Step-by-Step Solution
Solution:
  1. Step 1: Understand the goal

    We want a list containing only the integers from the mixed list.
  2. Step 2: Analyze options

    var ints = mixed.Where(item => item is int i).Select(item => (int)item).ToList(); uses pattern matching but incorrectly selects (int)item without using the matched variable. var ints = mixed.OfType().ToList(); uses OfType<int>() which filters and casts correctly. var ints = mixed.Where(item => item is int i).Select(i => i).ToList(); tries to select i but i is not in scope in the lambda. var ints = mixed.Select(item => item as int).ToList(); uses as int which is invalid because int is a value type.
  3. Final Answer:

    var ints = mixed.OfType<int>().ToList(); -> Option C
  4. Quick Check:

    Use OfType<T>() to filter and cast [OK]
Quick Trick: OfType() filters and casts in one step [OK]
Common Mistakes:
MISTAKES
  • Using 'as' with value types
  • Incorrectly using pattern variable in LINQ
  • Casting without filtering causing exceptions

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More C Sharp (C#) Quizzes