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!
In order to make usable programs in C or C++, you will need a compiler. A compiler converts source code - the actual instructions typed by the programmer - into an executable file. Numerous compilers are available for C and C++.
C programming language is a machine-independent programming language that is mainly used to create many types of applications and operating systems such as Windows, and other complicated programs such as the Oracle database, Git, Python interpreter, and games and is considered a programming foundation in the process of ...
C programming has a very good career like opportunities in different field like robotics, Artificial intelligence, machine learning, etc. The C programmers not only work in the field of computer only, but they can also pursue their career in Education, teaching, Government sectors, etc.
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.
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.
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