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
Release: 2025-01-04 03:24:40
Original
572 people have browsed it

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" };
Copy after login

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);
Copy after login

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 });
    ...
}
Copy after login

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);
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template