In C# 3.0, you can create anonymous classes using the following syntax:
var o = new { Id = 1, Name = "Foo" };
You might want to add these anonymous classes to a generic list, such as:
var o = new { Id = 1, Name = "Foo" }; var o1 = new { Id = 2, Name = "Bar" }; List list = new List(); list.Add(o); list.Add(o1);
Or you might want to dynamically create and add anonymous classes to the list, such as:
List<var> list = new List<var>(); while (...) { ... list.Add(new { Id = x, Name = y }); ... }
To achieve this, you can use type inference and call a generic method, either as an extension method or a custom method. Here are some examples:
// Using an extension method var list = new[] { o, o1 }.ToList(); // Using a custom method public static List<T> CreateList<T>(params T[] elements) { return new List<T>(elements); } var list = CreateList(o, o1);
The above is the detailed content of How Can I Add Anonymous Classes to a Generic List in C#?. For more information, please follow other related articles on the PHP Chinese website!