LinqToDataTable

/// <summary>
 ///  下面通过一个方法来实现返回DataTable类型 
 /// LINQ返回DataTable类型
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="varlist"></param>
/// <returns></returns>
        public static DataTable ToDataTable<T>(IEnumerable<T> varlist)
        {
            DataTable dtReturn = new DataTable();
            // column names 
            PropertyInfo[] oProps = null;
            if (varlist == null)
                return dtReturn;
            foreach (T rec in varlist)
            {
                if (oProps == null)
                {
                   oProps = ((Type)rec.GetType()).GetProperties();
                    foreach (PropertyInfo pi in oProps)
                    {
                        Type colType = pi.PropertyType;
                        if ((colType.IsGenericType) && (colType.GetGenericTypeDefinition()
                             == typeof(Nullable<>)))
                        {
                            colType = colType.GetGenericArguments()[0];
                        }
                        dtReturn.Columns.Add(new DataColumn(pi.Name, colType));
                    }
                }
                DataRow dr = dtReturn.NewRow();
                foreach (PropertyInfo pi in oProps)
                {
                    dr[pi.Name] = pi.GetValue(rec, null) == null ? DBNull.Value : pi.GetValue
                    (rec, null);
                }
                dtReturn.Rows.Add(dr);
            }
            return dtReturn;
        }

 

 

 

public static System.Data.DataTable LinqToDataTable<T>(IEnumerable<T> data)
        {
            var dt = new System.Data.DataTable();
            var ps = typeof(T).GetProperties().ToList();
            ps.ForEach(p => dt.Columns.Add(p.Name, p.PropertyType));

            foreach (T t in data)
            {
                var dr = dt.NewRow();
                var vs = from p in ps select p.GetValue(t, null);
                var ls = vs.ToList();
                int i = 0;
                ls.ForEach(c => dr[i++] = c);
                dt.Rows.Add(dr);
            }
            return dt;
        }

        public static System.Data.DataTable ToDataTable<T>(IEnumerable<T> data)
        {
            var dt = new System.Data.DataTable();
            var ps = System.ComponentModel.TypeDescriptor.GetProperties(typeof(T));
            foreach (System.ComponentModel.PropertyDescriptor dp in ps)
                dt.Columns.Add(dp.Name, dp.PropertyType);
            foreach (T t in data)
            {
                var dr = dt.NewRow();
                foreach (System.ComponentModel.PropertyDescriptor dp in ps)
                    dr[dp.Name] = dp.GetValue(t);
                dt.Rows.Add(dr);
            }
            return dt;
        }

你可能感兴趣的:(LinqToDataTable)