I am calling a method that returns a List variable that contains a c# Anonymous Type objects. For example:
List<object> list = new List<object>();
foreach ( Contact c in allContacts ) {
list.Add( new {
ContactID = c.ContactID,
FullName = c.FullName
});
}
return list;
How do I reference this type properties in the code I am working on like for example
foreach ( object o in list ) {
Console.WriteLine( o.ContactID );
}
I know that my sample is not possible, I have only wrote that way to say that I need to identify each property of the anonymous type exactly.
Thanks!
Solution:
Not just one of the answer is correct and/or suggest a working solution. I have ended up to using Option 3 of Greg answer. And I learned something very interesting regarding the dynamic
in .NET 4.0!
You can't return a list of an anonymous type, it will have to be a list of object
. Thus you will lose the type information.
Option 1
Don't use an anonymous type. If you are trying to use an anonymous type in more than one method, then create a real class.
Option 2
Don't downcast your anonymous type to object
. (must be in one method)
var list = allContacts
.Select(c => new { c.ContactID, c.FullName })
.ToList();
foreach (var o in list) {
Console.WriteLine(o.ContactID);
}
Option 3
Use the dynamic keyword. (.NET 4 required)
foreach (dynamic o in list) {
Console.WriteLine(o.ContactID);
}
Option 4
Use some dirty reflection.