Bird
Raised Fist0

Given a list of products with Category and Price, how do you sort products by category ascending and then by price descending?

hard🚀 Application Q9 of Q15
C Sharp (C#) - LINQ Fundamentals
Given a list of products with Category and Price, how do you sort products by category ascending and then by price descending?
Aproducts.Sort(p => p.Category, p => p.Price);
Bproducts.OrderByDescending(p => p.Category).ThenBy(p => p.Price);
Cproducts.OrderBy(p => p.Price).ThenByDescending(p => p.Category);
Dproducts.OrderBy(p => p.Category).ThenByDescending(p => p.Price);
Step-by-Step Solution
Solution:
  1. Step 1: Identify sorting order for each property

    Category ascending, Price descending.
  2. Step 2: Use OrderBy for category and ThenByDescending for price

    Correct chaining is OrderBy then ThenByDescending.
  3. Final Answer:

    products.OrderBy(p => p.Category).ThenByDescending(p => p.Price); -> Option D
  4. Quick Check:

    OrderBy then ThenByDescending for mixed order sorting [OK]
Quick Trick: Chain OrderBy then ThenByDescending for mixed ascending/descending [OK]
Common Mistakes:
MISTAKES
  • Swapping ascending and descending order
  • Using OrderByDescending first incorrectly
  • Trying to use Sort with multiple keys

Want More Practice?

15+ quiz questions · All difficulty levels · Free

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