In C# 3.0, anonymous classes provide a convenient way of creating lightweight objects with dynamically generated properties. However, the question arises: can these anonymous classes be incorporated into generic lists?
To address this, you have a few options:
Initialization Array: You can create an anonymous class array and then use the .ToList() method to convert it to a list.
var list = new[] { o, o1 }.ToList();
Generic Method with Type Inference: By using a generic method, you can avoid explicitly specifying the list type.
public static List<T> CreateList<T>(params T[] elements) { return new List<T>(elements); } var list = CreateList(o, o1);
Let's provide some working examples:
// Example 1: Adding to an Existing List var list = new List<dynamic>(); list.Add(new { Id = 1, Name = "Foo" }); list.Add(new { Id = 2, Name = "Bar" }); // Example 2: Populating a List in a Loop var list = new List<dynamic>(); while (...) { list.Add(new { Id = x, Name = y }); }
In these scenarios, the anonymous classes are effectively added to the generic list. Please note that the type of the list remains dynamic, allowing for the addition of anonymous classes with different property sets without type validation.
The above is the detailed content of Can Anonymous Classes Be Added to Generic Lists in C#?. For more information, please follow other related articles on the PHP Chinese website!