Share via


Need to Loop through a dynamic variable

Question

Sunday, August 7, 2016 6:03 AM

I have A dynamic variable which held a list object .
List object Could hold any class object like List<Employee>, List<students>, List<movies>
I need a generic function to print all the rows in the list .

I am able to fetch Field name 
how to fetch multiple rows and print 

foreach (var prop in data.GetType().GetProperties(BindingFlags.Instance | BindingFlags.Public))

{
//Console.WriteLine("Name: {0}, Value: {1}", prop.Name, prop.GetValue(data, null));
sbHead.Append("<th>" + prop.Name + "</th>");
 
}
Thanks 

All replies (4)

Tuesday, August 9, 2016 6:45 AM âś…Answered

Found the Solution Guys 

 public static void GenerateHtml(object obj)
        {
            string htmlData = "<table class='table table-bordered table - responsive table - hover'>";
            StringBuilder sbHeader = new StringBuilder();
            StringBuilder sbBody = new StringBuilder();

            foreach (PropertyInfo pi in obj.GetType().GetProperties(BindingFlags.Instance | BindingFlags.Public))
            {
                if (typeof(IList).IsAssignableFrom(pi.PropertyType))
                {
                    IList elms = (IList)pi.GetValue(obj, null);
                    if (elms != null)
                    {
                        sbHeader.Append(htmlData + "<thead><tr class='table-info'>");
                        foreach (PropertyDescriptor descriptor in TypeDescriptor.GetProperties(elms[0]))
                        {
                            sbHeader.Append("<th>" + descriptor.Name+"</th>");
                        }
                        sbHeader.Append("</tr></thead>");
                        sbBody.Append("<tbody>");
                        for (int i = 0; i < elms.Count; i++)
                        {
                            sbBody.Append("<tr class='table-active'>");
                            foreach (PropertyDescriptor descriptor in TypeDescriptor.GetProperties(elms[i]))
                            {
                                //string name=descriptor.Name;
                                //object value=descriptor.GetValue(elms[i]);
                                //Console.WriteLine("{0}={1}", name, value);
                                sbBody.Append("<td>" + Convert.ToString(descriptor.GetValue(elms[i])) + "</td>");
                            }
                            sbBody.Append("</tr>");
                        }
                        sbBody.Append("<tbody></table>");
                    }
                }
                else
                {
                    Console.WriteLine(pi.Name + "=" + pi.GetValue(obj, null));
                }
            }
            Console.WriteLine(sbHeader.ToString() + sbBody.ToString());
        }

Monday, August 8, 2016 1:43 AM

Are you saying that you know how to print one element of your list but you do not know how to print all elements?

When you say that you have a dynamic variable, do you mean that it is of type 'dynamic' or of type 'List<T>' or 'object' or something else?  Can you show us the declaration of this variable?  Can you show us how the variable is populated?

You seem to be saying that you have down the very difficult, complicated part of the program (using reflection to loop through the properties of a type) but that you do not know how to write a simple loop to iterate a list.  This doesn't seem likely, so any more information you have would assist people to help you with your problem.


Monday, August 8, 2016 6:35 AM

Hi arry.net ,

List object Could hold any class object like List<Employee>, List<students>, List<movies>
I need a generic function to print all the rows in the list .

Code below is for your reference :

    public class Employee
    {
        public int id;
        public string name;
    }

    public class Student
    {
        public int Stuid;
        public string Stuname;
    }

Test code:

            List<Employee> alist = new List<Employee>();
            List<Student> blist = new List<Student>();

            Employee e1 = new Employee();
            e1.id = 1;
            e1.name = "1";
            alist.Add(e1);
            Employee e2 = new Employee();
            e2.id = 2;
            e2.name = "2";
            alist.Add(e2);

            Student s1 = new Student();
            s1.Stuid = 1;
            s1.Stuname = "1";
            blist.Add(s1);
            Student s2 = new Student();
            s2.Stuid = 2;
            s2.Stuname = "2";
            blist.Add(s2);

            List<object> temp_list = new List<object>();
            temp_list.Add(alist);
            temp_list.Add(blist);

            var allObjects = temp_list
    .Select(l => l as IEnumerable<object>)  // try to cast to IEnumerable<object>
    .Where(l => l != null)                  // filter failed casts
    .SelectMany(l => l);                    // transform the list of lists into a single sequence of objects

            foreach (var o in allObjects)
            {
                
            }

Best Regards,

Nan Yu


Monday, August 8, 2016 10:05 AM

Sorry for not explaining the requirement properly 
I have 100 stored procedure which returns data which is uncertain (it could return 1 to n numbers of columns with single or multiple rows) 
I am using Entity framework which  returns me a class object or a list<> of object .
What I needed is to create a single function in which i can pass the output of my any StoredProcedure 
and regardless the structure of the data it generates an HTML (Which I return directly to UI) Also i need to access field name too.
So if my sp return 
 var result1 = DB.getServerDetailsBackupDefincation(servername);
 var result2 = DB.getServerDetailsStorageDevice(servername);
I want to send result in a fucntion which  will accpet result either as dynamic or as object .

private static void loop(object result)
{
}
private static void loop(dynamic result){
}
And now i have to access all the item in the list in result so i can loop through it 
and create a header with column name 
And rows if they  exists in result .

So far i am able to get the column name.

PropertyInfo[] propertyInfo = obj.GetType().GetProperties();
Type type=propertyInfo[2].GetMethod.ReturnType; /to access list type 
PropertyInfo[] propertyInfo1 = type.GetProperties();

foreach (PropertyInfo p in propertyInfo1)
{
Console.WriteLine(p.Name); //
}

I hope you understand what i need 
Thanks a lot for answering