datatable转换成list

protected void Page_Load(object sender, EventArgs e)
        {
            DataTable dt = new DataTable();
            dt.Columns.Add(new DataColumn("HI", typeof(System.Int32)));
            dt.Columns.Add(new DataColumn("OK", typeof(System.String)));
            dt.Columns.Add(new DataColumn("HAI", typeof(System.String)));
            dt.Rows.Add(1, "dlkjsf", "ldsjflskjd");
            dt.Rows.Add(2, "dlkjsf", "ldsjflskjd");
            dt.Rows.Add(3, "dlkjsf", "ldsjflskjd");
            dt.Rows.Add(4, "dlkjsf", "ldsjflskjd");
            Form1.MapDataTableToObjectList<A_Record>(dt);

        }
        public static List<TType> MapDataTableToObjectList<TType>(DataTable dt) where TType : new()
        {
            System.Data.DataColumnCollection columns = dt.Columns;
            int iColumnCount = columns.Count;
            int i;
            int j;
            TType ttype = new TType();
            Type elementType;
            elementType = ttype.GetType();
            System.Reflection.PropertyInfo[] publicProperties = elementType.GetProperties();
            List<TType> result = new List<TType>();
            if (publicProperties.Length == iColumnCount)
            {
                foreach (DataRow currentRow in dt.Rows)
                {
                    for (i = 0; i < iColumnCount; i++)
                    {
                        for (j = 0; j < publicProperties.Length; j++)
                        {
                            if (columns[i].ColumnName == publicProperties[j].Name)
                            {
                                publicProperties[j].SetValue(ttype, currentRow[i], null);
                            }
                        }
                    }
                    result.Add(ttype);
                    ttype = new TType();
                }
            }
            else
            {
                result = null;
            }
            return result;
        }

        public class A_Record
        {
            private int hi;
            private string ok;
            protected string hai;


            public int HI
            {
                get { return hi; }
                set { hi = value; }
            }

            public string OK
            {
                get { return ok; }
                set { ok = value; }
            }

            public string HAI
            {
                get { return hai; }
                set { hai = value; }
            }
        }

posted @ 2008-06-16 10:37  dada7357  阅读(1565)  评论(1编辑  收藏  举报