I am calling a method that returns a List variable that contains a c# Anonymous Type objects. For example:
ListYou cannot do this with anonymous types. Just create a Contact class/struct and use that.
List<object> list = new List<object>();
foreach ( Contact c in allContacts ) {
list.Add( c );
}
Then you can do this:
foreach ( var o in list ) {
Console.WriteLine( o.ContactID );
}
...or this:
foreach ( object o in list ) {
Console.WriteLine( ((Contact)o).ContactID ); //Gives intellisense
}
Of course you should in that case just do create a Contact list instead of an object list:
List<Contact> list = new List<Contact>();
foreach ( Contact c in allContacts ) {
list.Add( c );
}
EDIT: Missed essential part of the question. Now fixed.
EDIT: Changed answer yet again. See above.
i would use
allContacts
.Select(c => new { c.ContactID, c.FullName })
.ToList()
.ForEach(c => {
...do stuff;
});
then you dont need to declare at all. i believe that less declaration, less semi-colon leads to less bug
foreach ( var o in list ) {
Console.WriteLine( o.ContactID );
}
this will work only if list is IEnumerable<anonymous type>, like this:
var list = allContacts.Select(c => new {
ContactID = c.ContactID,
FullName = c.FullName
});
}
but you can't return anonymous types, because you must define return type (you can't return var) and anonymous types can't have names. you should create non-anonymous type if you with to pass it. Actually anonymous types should not be used too much, except for inside of queries.
replacing object with var in for each construct may work
list back
public static void Main()
{
foreach (object item in GetList())
{
var x = Cast(item, new { ContactID = 0, FullName = "" });
Console.WriteLine(x.ContactID + " " + x.FullName);
}
}
public static IEnumerable<object> GetList()
{
yield return new { ContactID = 4, FullName = "Jack Smith" };
yield return new { ContactID = 5, FullName = "John Doe" };
}
public static T Cast<T>(object obj, T type)
{
return (T)obj;
}
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.