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

Generic constraints (where clause) in C Sharp (C#) - Mini Project: Build & Apply

Choose your learning style9 modes available
Filtering Products with Generic Constraints in C#
📖 Scenario: You work in a store that sells different products. You want to keep a list of products and filter them based on their price.
🎯 Goal: Create a generic class that can filter products by price using a generic constraint with a where clause.
📋 What You'll Learn
Create a class Product with properties Name (string) and Price (decimal).
Create a generic class Filter<T> with a where clause that restricts T to be Product or a subclass.
Add a method FilterByPrice in Filter<T> that returns products with price less than a given value.
Create a list of Product objects with exact values.
Use the FilterByPrice method to get products cheaper than a specific price and print their names.
💡 Why This Matters
🌍 Real World
Stores and e-commerce platforms often filter products by price or other attributes. Using generic constraints helps create reusable filtering classes.
💼 Career
Understanding generic constraints and filtering data is important for software developers working with collections, databases, and APIs.
Progress0 / 4 steps
1
Create the Product class and product list
Create a class called Product with two public properties: Name of type string and Price of type decimal. Then create a list called products with these exact entries: new Product { Name = "Pen", Price = 1.5m }, new Product { Name = "Notebook", Price = 3.0m }, new Product { Name = "Backpack", Price = 25.0m }.
C Sharp (C#)
Need a hint?

Define the Product class with two properties. Then create a List<Product> with the exact products.

2
Add generic Filter class with where constraint
Create a generic class called Filter<T> with a where clause that restricts T to be Product or a subclass. Inside it, add a public field items of type List<T>.
C Sharp (C#)
Need a hint?

Use where T : Product to restrict the generic type. Add a constructor to set the items field.

3
Add FilterByPrice method to Filter class
Inside the Filter<T> class, add a method called FilterByPrice that takes a decimal maxPrice parameter and returns a List<T> of items with Price less than maxPrice. Use LINQ Where to filter.
C Sharp (C#)
Need a hint?

Use LINQ Where to select items with price less than maxPrice.

4
Use Filter class and print filtered product names
In the Main method, create an instance of Filter<Product> called filter using the products list. Then call FilterByPrice with 5.0m and store the result in cheapProducts. Finally, print the Name of each product in cheapProducts on separate lines.
C Sharp (C#)
Need a hint?

Create the Filter<Product> instance and call FilterByPrice(5.0m). Print each product's Name from the result.