110,534
社区成员
发帖
与我相关
我的任务
分享
/// <summary>
/// IList转为DataSet
/// </summary>
/// <typeparam name="T">List数据类型</typeparam>
/// <param name="List">Ilist集合</param>
/// <param name="PropertyName">待转换属性名数组</param>
/// <returns></returns>
public static DataSet ToDataSet<T>(IList<T> List, params string[] PropertyName)
{
List<string> propertyNameList = new List<string>();
if (PropertyName != null)
propertyNameList.AddRange(PropertyName);
DataSet result = new DataSet();
System.Data.DataTable DataTable = new System.Data.DataTable();
if (List.Count > 0)
{
PropertyInfo[] propertys = List[0].GetType().GetProperties();
foreach (PropertyInfo pi in propertys)
{
if (propertyNameList.Count == 0)
{
DataTable.Columns.Add(pi.Name, pi.PropertyType);
}
else
{
if (propertyNameList.Contains(pi.Name))
DataTable.Columns.Add(pi.Name, pi.PropertyType);
}
}
for (int i = 0; i < List.Count; i++)
{
ArrayList tempList = new ArrayList();
foreach (PropertyInfo pi in propertys)
{
if (propertyNameList.Count == 0)
{
object obj = pi.GetValue(List, null);
tempList.Add(obj);
}
else
{
if (propertyNameList.Contains(pi.Name))
{
object obj = pi.GetValue(List, null);
tempList.Add(obj);
}
}
}
object[] array = tempList.ToArray();
DataTable.LoadDataRow(array, true);
}
}
result.Tables.Add(DataTable);
return result;
}
/// <summary>
/// DataSet转为IList
/// </summary>
/// <typeparam name="T">数据类型</typeparam>
/// <param name="DataSet">DataSet数据集</param>
/// <param name="TableIndex">DataSet数据集中表的索引</param>
/// <returns></returns>
public static IList<T> DataSetToIList<T>(DataSet DataSet, int TableIndex)
{
if (DataSet == null || DataSet.Tables.Count < 0)
return null;
if (TableIndex > DataSet.Tables.Count - 1)
return null;
if (TableIndex < 0)
TableIndex = 0;
System.Data.DataTable dt = DataSet.Tables[TableIndex];
IList<T> result = new List<T>();
for (int j = 0; j < dt.Rows.Count; j++)
{
T t = (T)Activator.CreateInstance(typeof(T));
PropertyInfo[] propertys = t.GetType().GetProperties();
foreach (PropertyInfo pi in propertys)
{
for (int i = 0; i < dt.Columns.Count; i++)
{
if (pi.Name.Equals(dt.Columns[i].ColumnName))
{
if (dt.Rows[j][i] != DBNull.Value)
pi.SetValue(t, dt.Rows[j][i], null);
else
pi.SetValue(t, null, null);
break;
}
}
}
result.Add(t);
}
return result;
}
select * from table