C#扩展方法将任意集合转成DataSet

    xiaoxiao2021-08-28  110

    /// <summary> /// 转换成DataSet,若被转换对象为Null,则返回Null。 /// </summary> /// <param name="obj">一个对象实例</param> /// <returns>返回DataSet,若被转换对象为Null,则返回Null。</returns> public static DataSet ToDataSet(this object obj) { if (obj == null) return null; if (obj is DataSet) { return obj as DataSet; } DataSet ds = new DataSet(); if (obj is DataTable) { ds.Tables.Add(obj as DataTable); return ds; } DataTable dt = new DataTable(); ds.Tables.Add(dt); IEnumerable<object> list = obj as IEnumerable<object>; if (list == null) { var properties = obj.GetType().GetProperties().ToList(); if (properties.Count == 0) return null; properties.ForEach(s => dt.Columns.Add(s.Name, Nullable.GetUnderlyingType(s.PropertyType) ?? s.PropertyType)); var row = dt.NewRow(); properties.ForEach(s => row[s.Name] = s.GetValue(obj, null) ?? DBNull.Value); dt.Rows.Add(row); } else { try { var properties = list.ToList()[0].GetType().GetProperties().ToList(); properties.ForEach(s => dt.Columns.Add(s.Name, Nullable.GetUnderlyingType(s.PropertyType) ?? s.PropertyType)); foreach (var i in list) { var row = dt.NewRow(); properties.ForEach(s => row[s.Name] = s.GetValue(i, null) ?? DBNull.Value); dt.Rows.Add(row); } } catch (Exception) { return null; } } return ds; }
    转载请注明原文地址: https://ju.6miu.com/read-677291.html

    最新回复(0)