Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to enumerate 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 I'm not doing it correctly.

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

like image 406
ossprologix Avatar asked Nov 30 '22 16:11

ossprologix


2 Answers

Use the var keyword in the foreach line as well, instead of the general object type. The compiler will then automatically resolve the anonymous type and all its members, so you can access the properties directly by name.

foreach (var o in items)
{
    Console.WriteLine(o.Name);
}
like image 106
BoltClock Avatar answered Dec 15 '22 05:12

BoltClock


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

Just use var and you'll have complete type support

like image 29
Guillaume Davion Avatar answered Dec 15 '22 05:12

Guillaume Davion