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;
}
}
/// 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;
}
}
相关文章推荐
- c#将List<T>转换成DataSet
- C#读取数据库返回泛型集合 把DataSet类型转换为List<T>泛型集合
- List<> 转换为Dataset的C#代码实现 解决Nullable问题
- C#读取数据库返回泛型集合 把DataSet类型转换为List<T>泛型集合
- c# Json List<T> DataTable 数据相互转换
- C#读取数据库返回泛型集合 把DataSet类型转换为List<T>泛型集合
- c# Json List<T> DataTable 数据相互转换
- c# List<实体>转换List<object>集合
- 【.Net码农】C# List<string>与String字符串相互转换
- 【C#】List<T>类型强制转换
- c# Json List<T> DataTable 数据相互转换
- 20140704-C#object/List<object>与json、xml之间的相互转换
- asp.net DataSet转换成List<model>[源码]
- Ilist<T> 转换成 DataSet
- C#将DataTable转换成单个T实体和List<T>集合
- C#中string[]数组和list<string>泛型的相互转换
- DataSet和List<T> 泛型之间互相转换
- DataSet和List<T> 泛型之间互相转换
- c# Json List<T> DataTable 数据相互转换
- C#中string[]数组和list<string>泛型的相互转换