Bird
0
0

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🚀 Application Q15 of 15
C Sharp (C#) - LINQ Fundamentals
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?
Aproducts.ToDictionary(p => p.Name, p => p.Price).Where(p => p.Value > 50);
Bproducts.Where(p => p.Price > 50).ToDictionary(p => p.Name, p => p.Price);
Cproducts.Select(p => new {p.Name, p.Price > 50}).ToDictionary(p => p.Name, p => p.Price);
Dproducts.Where(p => p.Price > 50).Select(p => p.Name).ToDictionary();
Step-by-Step Solution
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]
Quick Trick: Filter first, then use ToDictionary with key and value [OK]
Common Mistakes:
MISTAKES
  • Trying to filter after ToDictionary (invalid)
  • Selecting anonymous types instead of original objects
  • Calling ToDictionary without key/value selectors

Want More Practice?

15+ quiz questions · All difficulty levels · Free

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