Anonymous types allow you to create objects without defining a class. They are useful for projecting data into new shapes without the need to explicitly define a class.
Suppose you have a list of employees and you want to project a subset of their properties into a new type.
var employees = new List<Employee>
{
new Employee { Name = "John", Age = 30, Department = "HR" },
new Employee { Name = "Jane", Age = 25, Department = "IT" }
};
// Project into anonymous type
var result = employees
.Select(e => new
{
e.Name,
e.Age
});
foreach (var item in result)
{
Console.WriteLine($"Name: {item.Name}, Age: {item.Age}");
}
In this example, an anonymous type is created with Name and Age properties. The resulting result variable holds a collection of these anonymous types.