How to list through an anonymously typed collection?

This is what I have:

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

I feel like doing it wrong.

Is there an easier way to access properties of anonymous types in a collection?

+3
source share
5 answers

Use a keyword varin a string foreach, not a generic type object. Then the compiler will automatically resolve the anonymous type and all its members so that you can access the properties directly by name.

foreach (var o in items)
{
    Console.WriteLine(o.Name);
}
+18
source
var items = list.Select(x =>new { Name = x.Name });
        foreach (var o in items)
        {
            Console.WriteLine(o.Name);
        }

Just use var and you will have full type support.

+1
source

?

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

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

, .

+1

. , , .

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

list.Select(person => person.Name).ToList().ForEach(Console.WriteLine); 
+1

If you are still going to iterate over the entire anonymous collection, you can ToList()use it and use the method 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));
0
source

All Articles