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?
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);
}
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With