List轉換DataTable


/// <summary>
    /// 將泛類型集合List類轉換成DataTable
    /// </summary>
    /// <param name="list">泛類型集合</param>
    /// <returns></returns>
    public static DataTable ListToDataTable<T>(List<T> entitys)
    {
        //檢查實體集合不能為空
        if (entitys == null || entitys.Count < 1)
        {
            throw new Exception("需轉換的集合為空");
        }
        //取出第一個實體的所有Propertie
        Type entityType = entitys[0].GetType();
        PropertyInfo[] entityProperties = entityType.GetProperties();

        //生成DataTable的structure
        //生產代碼中,應將生成的DataTable結構Cache起來,此處略
        DataTable dt = new DataTable();
        for (int i = 0; i < entityProperties.Length; i++)
        {
            //dt.Columns.Add(entityProperties[i].Name, entityProperties[i].PropertyType);
            dt.Columns.Add(entityProperties[i].Name);
        }
        //將所有entity添加到DataTable中
        foreach (object entity in entitys)
        {
            //檢查所有的的實體都為同一類型
            if (entity.GetType() != entityType)
            {
                throw new Exception("要轉換的集合元素類型不一致");
            }
            object[] entityValues = new object[entityProperties.Length];
            for (int i = 0; i < entityProperties.Length; i++)
            {
                entityValues[i] = entityProperties[i].GetValue(entity, null);
            }
            dt.Rows.Add(entityValues);
        }
        return dt;
    }

  


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM