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.