对象集合转换为datatable


  private static DataTable ToDataTable(IList list)
        {
            DataTable result = new DataTable();
            if (list.Count > 0)
            {
                PropertyInfo[] propertys = list[0].GetType().GetProperties();
                foreach (PropertyInfo pi in propertys)
                {
                    if (pi.PropertyType.Name.IndexOf("Nullable") > -1)
                    {
                        result.Columns.Add(pi.Name, typeof(string));
                        continue;
                    }
                    result.Columns.Add(pi.Name, pi.PropertyType);
                }

                for (int i = 0; i < list.Count; i++)
                {
                    ArrayList tempList = new ArrayList();
                    foreach (PropertyInfo pi in propertys)
                    {
                        object obj = pi.GetValue(list[i], null);
                        tempList.Add(obj);
                    }
                    object[] array = tempList.ToArray();

                    result.LoadDataRow(array, true);
                }
            }
            return result;
        }
posted @ 2010-05-25 16:24  左少白  阅读(323)  评论(0编辑  收藏  举报