您的位置:首页 > 编程语言 > C#

c#将List<T>转换成DataSet

2017-06-18 16:50 375 查看
/// <summary>

/// List<T> 转换成DataSet

/// </summary>

/// <typeparam name="T">对象</typeparam>

/// <param name="list">集合</param>

/// <returns>DataSet</returns>

public static DataSet ConvertToDataSet<T>(List<T> list)

{

if (list == null || list.Count <= 0)

{

return null;

}

DataSet ds = new DataSet();

DataTable dt = new DataTable(typeof(T).Name);

DataColumn column;

DataRow row;

System.Reflection.PropertyInfo[] myPropertyInfo = typeof(T).GetProperties(System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Instance);

foreach (T t in list)

{

if (t == null)

{

continue;

}

row = dt.NewRow();

for (int i = 0, j = myPropertyInfo.Length; i < j; i++)

{

System.Reflection.PropertyInfo pi = myPropertyInfo[i];

string name = pi.Name;

if (dt.Columns[name] == null)

{

column = new DataColumn(name, pi.PropertyType);

dt.Columns.Add(column);

}

row[name] = pi.GetValue(t, null);

}

dt.Rows.Add(row);

}

ds.Tables.Add(dt);

return ds;

}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: