C# 匿名类的通用列表

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/612689/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-04 10:16:10  来源:igfitidea点击:

A generic list of anonymous class

c#.netgenericsanonymous-types

提问by DHornpout

In C# 3.0 you can create anonymous class with the following syntax

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

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

Is there a way to add these anonymous class to a generic list?

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

Example:

例子:

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);

Another Example:

另一个例子:

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

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

采纳答案by Jon Skeet

You could do:

你可以这样做:

var list = new[] { o, o1 }.ToList();

There are lots of ways of skinning this cat, but basically they'll all use type inference somewhere - which means you've got to be calling a generic method (possibly as an extension method). Another example might be:

有很多方法可以给这只猫剥皮,但基本上它们都会在某处使用类型推断 - 这意味着您必须调用通用方法(可能作为扩展方法)。另一个例子可能是:

public static List<T> CreateList<T>(params T[] elements)
{
     return new List<T>(elements);
}

var list = CreateList(o, o1);

You get the idea :)

你明白了:)

回答by Jeff Moser

Not exactly, but you can say List<object>and things will work. However, list[0].Idwon't work.

不完全是,但你可以说List<object>,事情会奏效的。但是,list[0].Id不会工作。

This will work at runtimein C# 4.0 by having a List<dynamic>, that is you won't get IntelliSense.

这将在 C# 4.0中运行时通过具有List<dynamic>,即您不会获得智能感知。

回答by erikkallen

I guess

我猜

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

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

will work.

将工作。

You might also consider writing it like this:

你也可以考虑这样写:

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

回答by Jermismo

You can do it this way:

你可以这样做:

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

var array = new[] { o, o1 };
var list = array.ToList();

list.Add(new { Id = 3, Name = "Yeah" });

It seems a little "hacky" to me, but it works - if you really need to have a list and can't just use the anonymous array.

这对我来说似乎有点“hacky”,但它有效 - 如果你真的需要一个列表并且不能只使用匿名数组。

回答by Dutt

Here is the answer.

这是答案。

string result = String.Empty;

var list = new[]
{ 
    new { Number = 10, Name = "Smith" },
    new { Number = 10, Name = "John" } 
}.ToList();

foreach (var item in list)
{
    result += String.Format("Name={0}, Number={1}\n", item.Name, item.Number);
}

MessageBox.Show(result);

回答by Jakob Flygare

Instead of this:

取而代之的是:

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);

You could do this:

你可以这样做:

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

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

However, you will get a compiletime error if you try to do something like this in another scope, although it works at runtime:

但是,如果您尝试在另一个范围内执行类似的操作,则会出现编译时错误,尽管它在运行时有效:

private List<object> GetList()
{ 
    List<object> list = new List<object>();
    var o = new { Id = 1, Name = "Foo" }; 
    var o1 = new { Id = 2, Name = "Bar" }; 
    list.Add(o); 
    list.Add(o1);
    return list;
}

private void WriteList()
{
    foreach (var item in GetList()) 
    { 
        Console.WriteLine("Name={0}{1}", item.Name, Environment.NewLine); 
    }
}

The problem is that only the members of Object are available at runtime, although intellisense will show the properties idand name.

问题是只有 Object 的成员在运行时可用,尽管智能感知会显示属性idname

In .net 4.0 a solution is to use the keyword dynamicistead of objectin the code above.

在 .net 4.0 中,解决方案是在上面的代码中使用关键字dynamic 而不是object

Another solution is to use reflection to get the properties

另一种解决方案是使用反射来获取属性

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

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            Program p = new Program();
            var anonymous = p.GetList(new[]{
                new { Id = 1, Name = "Foo" },       
                new { Id = 2, Name = "Bar" }
            });

            p.WriteList(anonymous);
        }

        private List<T> GetList<T>(params T[] elements)
        {
            var a = TypeGenerator(elements);
            return a;
        }

        public static List<T> TypeGenerator<T>(T[] at)
        {
            return new List<T>(at);
        }

        private void WriteList<T>(List<T> elements)
        {
            PropertyInfo[] pi = typeof(T).GetProperties();
            foreach (var el in elements)
            {
                foreach (var p in pi)
                {
                    Console.WriteLine("{0}", p.GetValue(el, null));
                }
            }
            Console.ReadLine();
        }
    }
}

回答by user_v

Here is my attempt.

这是我的尝试。

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

I came up with this when I wrote something similar for making a Anonymous List for a custom type.

当我编写类似的东西来为自定义类型制作匿名列表时,我想到了这一点。

回答by morlock

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

回答by Ravi Saini

static void Main()
{
    List<int> list = new List<int>();
    list.Add(2);
    list.Add(3);
    list.Add(5);
    list.Add(7);
}

回答by MalachiteBR

You can do this in your code.

您可以在代码中执行此操作。

var list = new[] { new { Id = 1, Name = "Foo" } }.ToList();
list.Add(new { Id = 2, Name = "Bar" });