Code代码片断(5do8)

GDI+控件线程IO流ADO.NET接口类,函数语法

新主题
c# 获取ip,硬盘序列号,M...
IList转成DataSet
C# 泛型
说话自由

首页 » .NET/C# » 接口 »

IList转成DataSet

标签: IList DataSet Reflection


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;
    }

}

ccdot写于2008-9-7 17:32:03

如果愿意,请留下你观点或者感受...
称呼*
内容*
验证码*