Solved

Cast List<Object> to List<MyClass>

Posted on 2013-05-28
4
632 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 3
4 Comments
 
LVL 42

Accepted Solution

by:
sedgwick earned 500 total points
ID: 39200950
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
ID: 39200952
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
ID: 39200955
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
ID: 39200956
sorry, just saw this.  I will accept this answer
0

Featured Post

Guide to Performance: Optimization & Monitoring

Nowadays, monitoring is a mixture of tools, systems, and codes—making it a very complex process. And with this complexity, comes variables for failure. Get DZone’s new Guide to Performance to learn how to proactively find these variables and solve them before a disruption occurs.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Recently while returning home from work my wife (another .NET developer) was murmuring something. On further poking she said that she has been assigned a task where she has to serialize and deserialize objects and she is afraid of serialization. Wha…
This article shows how to deploy dynamic backgrounds to computers depending on the aspect ratio of display
Attackers love to prey on accounts that have privileges. Reducing privileged accounts and protecting privileged accounts therefore is paramount. Users, groups, and service accounts need to be protected to help protect the entire Active Directory …
Finding and deleting duplicate (picture) files can be a time consuming task. My wife and I, our three kids and their families all share one dilemma: Managing our pictures. Between desktops, laptops, phones, tablets, and cameras; over the last decade…

730 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