通过 NHibernate 查询返回的表数据通常都是 IList<T>,但在实际使用中有些数据控件在数据绑定上对IList的支持并不是很好,所以有时候将IList转换成DataSet还是有必要的。在 Vinson的Blogs中提到了怎么 将IList转换成DataSet,可惜源码是VB.NET的。 下面是我根据 IList转换成DataSet中的VB.NET源码转换成C#,由于现在做项目是用 VS 2005 ,所以也对其改进,让它支持C#2.0 中的泛型。 代码如下: using System;using System.Data;public class NHibernateHelper{ /**//// <summary> /// Ilist<T> 转换成 DataSet /// </summary> /// <param name="list"></param> /// <returns></returns> public static DataSet ConvertToDataSet<T>(IList<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; }}