在c# 3.0中,您可以使用以下语法创建匿名类

var o = new { Id = 1, Name = "Foo" };

有没有办法将这些匿名类添加到泛型列表中?

例子:

var o = new { Id = 1, Name = "Foo" };
var o1 = new { Id = 2, Name = "Bar" };

List<var> list = new List<var>();
list.Add(o);
list.Add(o1);

另一个例子:

List<var> list = new List<var>();

while (....)
{
    ....
    list.Add(new {Id = x, Name = y});
    ....
}

当前回答

下面是另一种创建匿名类型列表的方法,它允许你从一个空列表开始,但仍然可以访问智能感知。

var items = "".Select( t => new {Id = 1, Name = "foo"} ).ToList();

如果您想保留第一项,只需在字符串中放入一个字母。

var items = "1".Select( t => new {Id = 1, Name = "foo"} ).ToList();

其他回答

var list = new[]{
new{
FirstField = default(string),
SecondField = default(int),
ThirdField = default(double)
}
}.ToList();
list.RemoveAt(0);

我猜

List<T> CreateEmptyGenericList<T>(T example) {
    return new List<T>();
}

void something() {
    var o = new { Id = 1, Name = "foo" };
    var emptyListOfAnonymousType = CreateEmptyGenericList(o);
}

将工作。

你也可以考虑这样写:

void something() {
    var String = string.Emtpy;
    var Integer = int.MinValue;
    var emptyListOfAnonymousType = CreateEmptyGenericList(new { Id = Integer, Name = String });
}

使用反射

关于此主题的Microsoft文档。

using System;
using System.Collections;
using System.Collections.Generic;

var anonObj = new { Id = 1, Name = "Foo" };
var anonType = anonObj.GetType();

var listType = typeof(List<>);

// We know that List<> have only one generic argument, so we do this:
var contructed = listType.MakeGenericType(anonType);

// Create instance
var instance = Activator.CreateInstance(contructed);

// Using it
var list = (IList)instance;
list.Add(anonObj);

对于Dictionary<,>,您需要传递2个参数 例:dicType。MakeGenericType(type1, type2)

对于带有约束的泛型类型(其中T: struct), 我们需要做更多的核实。查看微软文档来学习如何操作。

您可以创建一个动态列表。

List<dynamic> anons=new List<dynamic>();
foreach (Model model in models)
{
   var anon= new
   {
      Id = model.Id,
      Name=model.Name
   };
   anons.Add(anon);
}

"dynamic"由第一个添加的值初始化。

下面是我的尝试。

List<object> list = new List<object> { new { Id = 10, Name = "Testing1" }, new {Id =2, Name ="Testing2" }}; 

当我为自定义类型编写类似的匿名列表时,我想到了这个方法。