Solved

Cast List<Object> to List<MyClass>

Posted on 2013-05-28
4
535 Views
Last Modified: 2013-05-28
Hi,

I have to write an ADO.Net Context, and rather than repetitively setting properties for each object, I decided to have a function that is passed an object as a template, opens a reader, then iterates through the properties of the object, setting them to the corresponding reader value.

This works absolutely great, however I'm not sure how to cast the returned List<object> to List<MyClass>

Here's the code:

Convert to List
public static List<object> ConvertToList(string SQL, Dictionary<string, dynamic> Parameters, string ConnectionString, object template)
        {
            SqlConnection conn = new SqlConnection(ConnectionString);
            IDbCommand cmd = conn.CreateCommand();
            List<object> ReturnList = new List<object>();
            Type convertType = template.GetType();
            DataTable dt = new DataTable();

            conn.Open();

            cmd.CommandText = SQL;
            cmd.CommandType = CommandType.StoredProcedure;


            //add parameters
            if (Parameters != null)
            {
                foreach (KeyValuePair<string, dynamic> prop in Parameters)
                {
                    IDataParameter param = cmd.CreateParameter();
                    param.ParameterName = prop.Key;
                    param.Value = prop.Value;

                    cmd.Parameters.Add(param);
                }
            }

            IDataReader reader = cmd.ExecuteReader();

            //dt.Load(reader);

            while (reader.Read())
            {
                object obj = Activator.CreateInstance(convertType);

                foreach (PropertyInfo propInfo in convertType.GetProperties())
                {
                    if (propInfo.CanRead)
                    {
                        dynamic val = null;

                        if (propInfo.PropertyType == typeof(string))
                        {
                            val = reader[propInfo.Name].ToString();
                        }
                        else if (propInfo.PropertyType == typeof(int))
                        {
                            val = Convert.ToInt32(reader[propInfo.Name]);
                        }
                        else if (propInfo.PropertyType == typeof(bool))
                        {
                            val = Convert.ToBoolean(reader[propInfo.Name]);
                        }
                        else if (propInfo.PropertyType == typeof(decimal))
                        {
                            val = Convert.ToDecimal(reader[propInfo.Name]);
                        }
                        else if (propInfo.PropertyType == typeof(DateTime))
                        {
                            val = Convert.ToDateTime(reader[propInfo.Name]);
                        }
                        else if (propInfo.PropertyType == typeof(Guid))
                        {
                            val = (Guid)reader[propInfo.Name];
                        }
                        else
                        {
                            Console.WriteLine("here");
                        }

                        convertType.GetProperty(propInfo.Name).SetValue(obj, val, null);
                    }
                }

                ReturnList.Add(obj);
            }

            reader.Close();
            conn.Close();

            return ReturnList;
        }

Open in new window


Set to Defined List
List<User> u = Extensions.ConvertToList("spListUsers", parameters, ConnectionString, new User());
            

Open in new window


Set to Defined list is the bit that isn't working



I've tried several things, but none seem to work.  Any ideas?
0
Comment
Question by:krapvag
  • 3
4 Comments
 
LVL 42

Accepted Solution

by:
sedgwick earned 500 total points
Comment Utility
using linq u can convert list of objects to list<MyClass> like the following:
List<MyClass> list = ReturnList.Select(n=>(MyClass)n).ToList();

Open in new window

0
 
LVL 1

Author Comment

by:krapvag
Comment Utility
Never mind, I have fixed it

Here it is incase anyone is curious

List<User> users = u.Select(f => (User)f).ToList();

Open in new window

0
 
LVL 1

Author Comment

by:krapvag
Comment Utility
I've requested that this question be closed as follows:

Accepted answer: 0 points for krapvag's comment #a39200952

for the following reason:

found solution myself
0
 
LVL 1

Author Closing Comment

by:krapvag
Comment Utility
sorry, just saw this.  I will accept this answer
0

Featured Post

How to run any project with ease

Manage projects of all sizes how you want. Great for personal to-do lists, project milestones, team priorities and launch plans.
- Combine task lists, docs, spreadsheets, and chat in one
- View and edit from mobile/offline
- Cut down on emails

Join & Write a Comment

This article describes relatively difficult and non-obvious issues that are likely to arise when creating COM class in Visual Studio and deploying it by professional MSI-authoring tools. It is assumed that the reader is already familiar with the cla…
More often than not, we developers are confronted with a need: a need to make some kind of magic happen via code. Whether it is for a client, for the boss, or for our own personal projects, the need must be satisfied. Most of the time, the Framework…
This video gives you a great overview about bandwidth monitoring with SNMP and WMI with our network monitoring solution PRTG Network Monitor (https://www.paessler.com/prtg). If you're looking for how to monitor bandwidth using netflow or packet s…
This video demonstrates how to create an example email signature rule for a department in a company using CodeTwo Exchange Rules. The signature will be inserted beneath users' latest emails in conversations and will be displayed in users' Sent Items…

744 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

15 Experts available now in Live!

Get 1:1 Help Now