Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/327.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 如何通过匿名类型的集合进行枚举?_C#_.net_Linq_Anonymous Types - Fatal编程技术网

C# 如何通过匿名类型的集合进行枚举?

C# 如何通过匿名类型的集合进行枚举?,c#,.net,linq,anonymous-types,C#,.net,Linq,Anonymous Types,这就是我所拥有的: List<Person> list = new List<Person>() { new Person { Name="test", Age=1 }, new Person { Name="tester", Age=2 } }; var items = list.Select(x => { return new { Name = x.Name }; }); foreach (object

这就是我所拥有的:

List<Person> list = new List<Person>()
{
    new Person { Name="test", Age=1 },
    new Person { Name="tester", Age=2 }
};

var items = list.Select(x =>
{
    return new
    {
        Name = x.Name
    };
});

foreach (object o in items)
{
    Console.WriteLine(o.GetType().GetProperty("Name").GetValue(o, null));
}
List List=新列表()
{
新人{Name=“test”,年龄=1},
新人{Name=“tester”,年龄=2}
};
变量项=列表。选择(x=>
{
还新
{
Name=x.Name
};
});
foreach(项目中的对象o)
{
WriteLine(o.GetType().GetProperty(“Name”).GetValue(o,null));
}
我觉得我做得不对


有没有更简单的方法来访问集合中匿名类型的属性?

foreach
行中也使用
var
关键字,而不是常规的
对象
类型。然后,编译器将自动解析匿名类型及其所有成员,因此您可以直接通过名称访问属性

foreach (var o in items)
{
    Console.WriteLine(o.Name);
}
只要使用var,您就可以获得完整的类型支持

为什么不只是这样呢

var items = list.Select(x => x.Name);

foreach (var o in items)
    Console.WriteLine(o);

您只得到一个字段,不需要创建另一个匿名类型。

如果您要遍历整个匿名集合,您可以
ToList()
它并使用
List.ForEach()
方法:

   List<Person> list = new List<Person>()
    {
        new Person { Name="test", Age=1},
        new Person { Name="tester", Age=2}
    };

   var items = list.Select(x =>
        {
            return new
            {
                Name = x.Name
            };

        }).ToList();

   items.ForEach(o => Console.WriteLine(o.Name));
List List=新列表()
{
新人{Name=“test”,年龄=1},
新人{Name=“tester”,年龄=2}
};
变量项=列表。选择(x=>
{
还新
{
Name=x.Name
};
}).ToList();
items.ForEach(o=>Console.WriteLine(o.Name));

前面的答案就足够了。 关于简化,请注意,您没有达到可能的最大简化。 你可以写

list.ForEach(person => Console.WriteLine(person.Name)); 


甚至
list.Select(x=>x.Name).ForEach(o=>Console.WriteLine(o))@BoltClock:我们不要太极端:)。不过你说得有道理。如果OP只想打印每个人的名字,其他什么都不想…@BoltClock:乍一看,我认为这就是他想要的。这就是为什么我把事情简化了这么多。@Dani:只是在没有ToList的情况下尝试了一下,我得到的结果是:错误'System.Collections.Generic.IEnumerable'不包含'ForEach'的定义,并且找不到接受'System.Collections.Generic.IEnumerable'类型的第一个参数的扩展方法'ForEach'(是否缺少using指令或程序集引用?+1。处理匿名类型是引入
var
关键字的原因。
list.ForEach(person => Console.WriteLine(person.Name)); 
list.Select(person => person.Name).ToList().ForEach(Console.WriteLine);