ossprologix
ossprologix

Reputation: 41

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?

Upvotes: 4

Views: 3293

Answers (5)

Ssithra
Ssithra

Reputation: 710

The previous answers are sufficient enough. Just about simplification, notice than you didn't reacj the maximal simplification possible. You can write

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

or

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

Upvotes: 1

BoltClock
BoltClock

Reputation: 723578

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

Upvotes: 18

Jackson Pope
Jackson Pope

Reputation: 14640

If you're going to iterate through the whole anonymous collection anyway, you could ToList() it and use the List.ForEach() method:

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

Upvotes: 0

alex
alex

Reputation: 3720

Why not just this?

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

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

You're only getting a single field, no need to create another anonymous type.

Upvotes: 1

Guillaume Davion
Guillaume Davion

Reputation: 434

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

Upvotes: 1

Related Questions