Solved

Cast List<Object> to List<MyClass>

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

How Do You Stack Up Against Your Peers?

With today’s modern enterprise so dependent on digital infrastructures, the impact of major incidents has increased dramatically. Grab the report now to gain insight into how your organization ranks against your peers and learn best-in-class strategies to resolve incidents.

Question has a verified solution.

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

Suggested Solutions

The object model of .Net can be overwhelming at times – so overwhelming that quite trivial tasks often take hours of research. In this case, the task at hand was to populate the datagrid from SQL Server database in Visual Studio 2008 Windows applica…
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…
In an interesting question (https://www.experts-exchange.com/questions/29008360/) here at Experts Exchange, a member asked how to split a single image into multiple images. The primary usage for this is to place many photographs on a flatbed scanner…

856 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