.net c# 程序开发中,经常需要将集合转Datatable,方便后续处理
思路非常简单,只需要遍历属性,然后创建DataTable实体即可.
源码如下:
        public static DataTable CreateTable<T>(IList<T> list)
        {
            DataTable table = CreateTable<T>();
            Type entityType = typeof(T);
            System.Reflection.PropertyInfo[] plist = entityType.GetProperties();
            foreach (T item in list)
            {
                DataRow row = table.NewRow();
                for (int i = 0; i < plist.Length; i++)
                {
                    object[] atts = plist[i].GetCustomAttributes(false);
                    bool pignore = false;
                    for (int j = 0; j < atts.Length; j++) if (atts[j].ToString() == "nottablecolum") { pignore = true; break; }
                    if (pignore) continue;
                    object pvalue = plist[i].GetValue(item, null);
                    if (pvalue == null || ((pvalue is DateTime) && (DateTime)pvalue == DateTime.MinValue)) { pvalue = DBNull.Value; }
                    row[plist[i].Name] = pvalue;
                }
                table.Rows.Add(row);
            }
            return table;
        }
调用代码:
        private void zbtntest_Click(object sender, EventArgs e)
        {
            List<DataTest> list = new List<DataTest>();
            for (int i = 1; i <= 50; i++)
            {
                list.Add(new DataTest() { name = "名称" + i.ToString(), des = "描述" + i.ToString(), count = i + 100 });
            }
            DataTable tb = ModelConst.CreateTable(list);
            var fff = "";
        }
        public class DataTest
        {
            /// <summary>
            /// 名称
            /// </summary>
            public string name { get; set; }
            /// <summary>
            /// 描述
            /// </summary>
            public string des { get; set; }
            /// <summary>
            /// 数量
            /// </summary>
            [ModelConst.ShowName("数量")]
            public int count { get; set; }
        }
效果如下:


