Home >Backend Development >C++ >How Can I Add Anonymous Classes to a Generic List in C#?

How Can I Add Anonymous Classes to a Generic List in C#?

Susan Sarandon
Susan SarandonOriginal
2025-01-04 03:24:40610browse

How Can I Add Anonymous Classes to a Generic List in C#?

Creating a Generic List of Anonymous Classes

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn