Solved

Cast List<Object> to List<MyClass>

Posted on 2013-05-28
4
560 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
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

Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

Question has a verified solution.

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

Many of us here at EE write code. Many of us write exceptional code; just as many of us write exception-prone code. As we all should know, exceptions are a mechanism for handling errors which are typically out of our control. From database errors, t…
A long time ago (May 2011), I have written an article showing you how to create a DLL using Visual Studio 2005 to be hosted in SQL Server 2005. That was valid at that time and it is still valid if you are still using these versions. You can still re…
Many functions in Excel can make decisions. The most simple of these is the IF function: it returns a value depending on whether a condition you describe is true or false. Once you get the hang of using the IF function, you will find it easier to us…
As a trusted technology advisor to your customers you are likely getting the daily question of, ‘should I put this in the cloud?’ As customer demands for cloud services increases, companies will see a shift from traditional buying patterns to new…

896 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

16 Experts available now in Live!

Get 1:1 Help Now