C# Multiple Objects - Working with Collections
Working with Multiple Objects
In real-world applications, you often need to work with multiple objects of the same class. C# provides various ways to create and manage collections of objects, including arrays, lists, and generic collection types.
Working with multiple objects allows you to process data in bulk, apply operations across sets of objects, and organize related information efficiently.
Creating and Managing Multiple Objects
Objects can be stored in arrays or generic collections like List
using System;
using System.Collections.Generic;
public class Student
{
public string Name { get; set; }
public int Age { get; set; }
public string Major { get; set; }
public void DisplayInfo()
{
Console.WriteLine($"Name: {Name}, Age: {Age}, Major: {Major}");
}
}
class Program
{
static void Main(string[] args)
{
Student student1 = new Student { Name = "Alice", Age = 20, Major = "Computer Science" };
Student student2 = new Student { Name = "Bob", Age = 21, Major = "Mathematics" };
Student student3 = new Student { Name = "Charlie", Age = 19, Major = "Physics" };
Student student4 = new Student { Name = "Diana", Age = 22, Major = "Biology" };
// Array example
Student[] studentArray = { student1, student2, student3, student4 };
Console.WriteLine("All Students (Array):");
foreach (Student student in studentArray)
{
student.DisplayInfo();
}
// List example
List<Student> studentList = new List<Student> { student1, student2, student3, student4 };
Console.WriteLine("\nStudents over 20 years old (List):");
foreach (Student student in studentList)
{
if (student.Age > 20)
{
Console.WriteLine($"- {student.Name} ({student.Age})");
}
}
Console.WriteLine("\nAfter incrementing all ages:");
foreach (Student student in studentList)
{
student.Age++;
student.DisplayInfo();
}
}
}
All Students (Array): Name: Alice, Age: 20, Major: Computer Science Name: Bob, Age: 21, Major: Mathematics Name: Charlie, Age: 19, Major: Physics Name: Diana, Age: 22, Major: Biology Students over 20 years old (List): - Bob (21) - Diana (22) After incrementing all ages: Name: Alice, Age: 21, Major: Computer Science Name: Bob, Age: 22, Major: Mathematics Name: Charlie, Age: 20, Major: Physics Name: Diana, Age: 23, Major: Biology
Advanced Multiple Object Operations
Collections of objects can be queried, filtered, grouped, and aggregated using LINQ and collection methods. This makes it easier to perform operations such as searching, calculating totals, and categorizing items.
using System;
using System.Collections.Generic;
using System.Linq;
public class Product
{
public string Name { get; set; }
public decimal Price { get; set; }
public int Quantity { get; set; }
public decimal GetTotalValue() => Price * Quantity;
public void DisplayInfo()
{
Console.WriteLine($"Product: {Name}, Price: {Price:C}, Quantity: {Quantity}, Total: {GetTotalValue():C}");
}
}
class Program
{
static void Main(string[] args)
{
List<Product> products = new List<Product>
{
new Product { Name = "Laptop", Price = 999.99m, Quantity = 5 },
new Product { Name = "Mouse", Price = 25.50m, Quantity = 20 },
new Product { Name = "Keyboard", Price = 75.00m, Quantity = 10 },
new Product { Name = "Monitor", Price = 299.99m, Quantity = 8 },
new Product { Name = "Headphones", Price = 149.99m, Quantity = 15 }
};
Console.WriteLine("All Products:");
foreach (Product product in products)
{
product.DisplayInfo();
}
var expensiveProducts = products.Where(p => p.Price > 100).ToList();
Console.WriteLine("\nExpensive Products (price > $100):");
foreach (Product product in expensiveProducts)
{
product.DisplayInfo();
}
decimal totalValue = products.Sum(p => p.GetTotalValue());
Console.WriteLine($"\nTotal Inventory Value: {totalValue:C}");
Product mostValuable = products.OrderByDescending(p => p.GetTotalValue()).First();
Console.WriteLine($"Most Valuable Product: {mostValuable.Name} ({mostValuable.GetTotalValue():C})");
var groupedProducts = products.GroupBy(p =>
{
if (p.Price < 50) return "Low ($0-50)";
else if (p.Price < 150) return "Medium ($50-150)";
else return "High ($150+)";
});
Console.WriteLine("\nProducts Grouped by Price Range:");
foreach (var group in groupedProducts)
{
Console.WriteLine($"\n{group.Key}:");
foreach (Product product in group)
{
Console.WriteLine($"- {product.Name}: {product.Price:C}");
}
}
}
}
All Products: Product: Laptop, Price: $999.99, Quantity: 5, Total: $4,999.95 Product: Mouse, Price: $25.50, Quantity: 20, Total: $510.00 Product: Keyboard, Price: $75.00, Quantity: 10, Total: $750.00 Product: Monitor, Price: $299.99, Quantity: 8, Total: $2,399.92 Product: Headphones, Price: $149.99, Quantity: 15, Total: $2,249.85 Expensive Products (price > $100): Product: Laptop, Price: $999.99, Quantity: 5, Total: $4,999.95 Product: Monitor, Price: $299.99, Quantity: 8, Total: $2,399.92 Product: Headphones, Price: $149.99, Quantity: 15, Total: $2,249.85 Total Inventory Value: $10,909.72 Most Valuable Product: Laptop ($4,999.95) Products Grouped by Price Range: High ($150+): - Laptop: $999.99 - Monitor: $299.99 Medium ($50-150): - Keyboard: $75.00 - Headphones: $149.99 Low ($0-50): - Mouse: $25.50