Reputation: 41
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
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
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
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
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
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