Best way to iterate through all the properties on a POCO Class.

Ronald Rex 1,666 Reputation points
2023-10-24T14:42:22.6866667+00:00
Hi Friends I was wondering how to iterate through all the properties on a POCO Class.




var o = new OrderPoco()
{
    OrderID = 1,
    CustomerID = "ABCDE",
    Shipper = 3
};

Console.WriteLine(o.CustomerID);   
Developer technologies | C#
{count} votes

3 answers

Sort by: Most helpful
  1. Anonymous
    2023-10-25T03:01:42.5566667+00:00

    Hi @Ronald Rex , Welcome to Microsoft Q&A,

    Are there any preconditions?

    To iterate over all properties of a POCO class, you can use reflection. In C#, you can use the "Type" class to get information about the properties of an object type.

    First use GetType() to get the type of the OrderPoco object. Then, use "GetProperties()" to retrieve an array of "PropertyInfo" objects that represent the class properties. Finally, iterate through the property information and use GetValue() to access the property's values and print them to the console.

    Public properties available only for POCO classes. If you have private or protected properties, you will need to modify your code accordingly. In addition, using reflection may reduce performance and needs to be used with caution.

    using System;
    using System.Reflection;
    
    class Program
    {
        static void Main()
        {
            var o = new OrderPoco()
            {
                OrderID = 1,
                CustomerID = "ABCDE",
                Shipper = 3
            };
    
            // Get the type of the object
            Type type = o.GetType();
    
            // Get all public properties of the object's type
            PropertyInfo[] properties = type.GetProperties();
    
            foreach (PropertyInfo property in properties)
            {
                // Get the name and value of each property
                string propertyName = property.Name;
                object propertyValue = property.GetValue(o);
    
                Console.WriteLine($"{propertyName}: {propertyValue}");
            }
        }
    }
    
    class OrderPoco
    {
        public int OrderID { get; set; }
        public string CustomerID { get; set; }
        public int Shipper { get; set; }
    }
    
    

    Best Regards,

    Jiale


    If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment". 

    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    1 person found this answer helpful.
    0 comments No comments

  2. KOZ6.0 6,735 Reputation points
    2023-10-24T16:02:41.0933333+00:00

    Choose the method you like.

    using System;
    using System.Collections.Generic;
    using System.ComponentModel;
    using System.Diagnostics;
    using System.Linq.Expressions;
    using System.Reflection;
    
    class OrderPoco
    {
        public int OrderID { get; set; }
        public string CustomerID { get; set; }
        public int Shipper { get; set; }
    }
    
    internal class Program
    {
        static void Main(string[] args) {
            var o = new OrderPoco() {
                OrderID = 1,
                CustomerID = "ABCDE",
                Shipper = 3
            };
            UseTypeDesctiptor(o);
            UseReflection(o);
            UseExpression(o);
            Console.ReadKey();
        }
    
        static void Watch(Action action) {
            var sw = new Stopwatch();
            sw.Start();
            for (int i = 0; i < LoopCount; i++) {
                action.Invoke();
            }
            sw.Stop();
            Console.WriteLine($"{sw.ElapsedMilliseconds} ms");
        }
    
        const int LoopCount = 1000000;
    
        static void UseTypeDesctiptor(object obj) {
            var properties = TypeDescriptor.GetProperties(obj);
            foreach (PropertyDescriptor property in properties) {
                string propertyName = property.Name;
                object propertyValue = property.GetValue(obj);
                Console.WriteLine($"{propertyName}: {propertyValue}");
            }
            Watch(() => {
                foreach (PropertyDescriptor pi in properties) {
                    var value = pi.GetValue(obj);
                }
            });
        }
    
        static void UseReflection<T>(T obj) {
            var properties = typeof(T).GetProperties();
            foreach (PropertyInfo pi in properties) {
                string propertyName = pi.Name;
                object propertyValue = pi.GetValue(obj);
                Console.WriteLine($"{propertyName}: {propertyValue}");
            }
            Watch(() => {
                foreach (var pi in properties) {
                    var value = pi.GetValue(obj);
                }
            });
        }
    
        static void UseExpression<T>(T obj) {
            var type = typeof(T);
            var parameter = Expression.Parameter(type);
            var dic = new Dictionary<string, Func<T, object>>();
            foreach (PropertyInfo pi in type.GetProperties()) {
                MemberExpression property = Expression.Property(parameter, pi);
                UnaryExpression conversion = Expression.Convert(property, typeof(object));
                Expression<Func<T, object>> lambda = Expression.Lambda<Func<T, object>>(conversion, parameter);
                Func<T, object> function = lambda.Compile();
                dic.Add(pi.Name, function);
            }
            foreach (var kp in dic) {
                Console.WriteLine($"{kp.Key}: {kp.Value(obj)}");
            }
            Watch(() => {
                foreach (var kp in dic) {
                    var value = kp.Value(obj);
                }
            });
        }
    }
    
    0 comments No comments

  3. Karen Payne MVP 35,586 Reputation points Volunteer Moderator
    2023-10-25T00:02:12.9766667+00:00

    What is the purpose of doing this?

    You can iterate as shown below to get property names.

    foreach (PropertyInfo p in typeof(OrderPoco).GetProperties())
    {
        string propertyName = p.Name;
       
    }
    

    And use the following method to get values. But still does not get what you want yet I see if as viable.

    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.